https://github.com/emahtab/binary-tree-right-side-view
Binary Tree Right Side View
https://github.com/emahtab/binary-tree-right-side-view
bfs binary-tree leetcode problem-solving
Last synced: 4 months ago
JSON representation
Binary Tree Right Side View
- Host: GitHub
- URL: https://github.com/emahtab/binary-tree-right-side-view
- Owner: eMahtab
- Created: 2020-02-01T17:28:37.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-02-01T17:41:22.000Z (over 5 years ago)
- Last Synced: 2025-02-02T03:26:16.263Z (5 months ago)
- Topics: bfs, binary-tree, leetcode, problem-solving
- Homepage:
- Size: 2.93 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Binary Tree Right Side View
## https://leetcode.com/problems/binary-tree-right-side-viewGiven a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
```
Example:
Given the below tree, right side view of the tree will be : [1, 3, 4, 6]
Explanation:1 <---
/ \
2 3 <---
\ \
5 4 <---
/
6 <---
```## Implementation :
```java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List rightSideView(TreeNode root) {
List list = new ArrayList<>();
if(root == null)
return list;
Queue queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode current = queue.poll();
if(i == size - 1)
list.add(current.val);
if(current.left != null)
queue.offer(current.left);
if(current.right != null)
queue.offer(current.right);
}
}
return list;
}
}
``````
Runtime Complexity = O(n), where n is the total number of nodes in the binary tree
Space Complexity = O(n), where n is the total number of nodes in the binary tree
```# References :
https://www.youtube.com/watch?v=jCqIr_tBLKs