Binary Tree Right Side View
Total Accepted: 44458 Total Submissions: 125991 Difficulty: Medium
Given A binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can SE E ordered from top to bottom.
For example:
Given The following binary tree,
1 <---/ 2 3 <---\ 5 4 <---
You should return [1, 3, 4]
.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide TagsTree Depth-first Search Breadth-first SearchHide Similar Problems(M) populating Next right pointers in each Node
Ideas:
Hierarchical traversal.
C + + code:
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class Solution {public: vector<int> rightsideview (treenode* root) { vector<int> ret; if (!root) return ret; Queue<treenode*> que; Que.push (root); while (!que.empty ()) { int size = Que.size (); for (int i = 0; i < size; i++) { TreeNode *tmp = Que.front (); Que.pop (); if (i = = 0) ret.push_back (tmp->val); if (tmp->right) Que.push (tmp->right); if (tmp->left) Que.push (tmp->left); } } return ret; }};
Java code:
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public list<integer> Rightsideview (TreeNode root) { list<integer> result = new arraylist<integer> (); if (root = null) return result; queue<treenode> queue = new linkedlist<treenode> (); Queue.offer (root); while (!queue.isempty ()) { int size = Queue.size (); for (int i=0;i<size;i++) { TreeNode tmp = Queue.poll (); if (i==0) Result.add (tmp.val); if (tmp.right! = null) Queue.offer (tmp.right); if (tmp.left! = null) Queue.offer (tmp.left);} } return result;} }
Leetcode:binary Tree right Side View