标签:
Given 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.
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
思路:
层次遍历。
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
标签:
原文地址:http://blog.csdn.net/itismelzp/article/details/51636280