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

Binary Tree Right Side View

时间:2016-08-03 06:43:15      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

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

分析:

这题有迷惑性,不要以为只是让你找出最右边的节点,如果左边节点比右边节点高,那么左边节点的右边部分也要输出来。

这题可以按层获取树的节点,然后把每层最右边的找出来。

Code from: http://www.programcreek.com/2014/04/leetcode-binary-tree-right-side-view-java/

/**
 * 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) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if (root == null) return result;

        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        while (queue.size() > 0) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode top = queue.poll();
                // the first element in the queue (right-most of the tree)
                if (i == 0) {
                    result.add(top.val);
                }
                // add right first
                if (top.right != null) {
                    queue.add(top.right);
                }
                // add left
                if (top.left != null) {
                    queue.add(top.left);
                }
            }
        }
        return result;
    }
}

 

Binary Tree Right Side View

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5731367.html

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