码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Binary Tree Right Side View

时间:2016-06-12 02:00:55      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

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




























思路:

层次遍历。


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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!