LeetCode:Binary Tree Right Side View

来源:互联网 发布:windows xp字体大小 编辑:程序博客网 时间:2024/06/06 02:00

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 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

Hide Tags
 Tree Depth-first Search Breadth-first Search
Hide Similar Problems
 (M) Populating Next Right Pointers in Each Node



























思路:

层次遍历。


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;    }}


0 0
原创粉丝点击