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

[LeetCode]Binary Tree Right Side View

时间:2015-11-29 14:58:05      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

第一个是BFS

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();
            result.add(queue.peek().val);
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.right != null) {
                    queue.offer(node.right);
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
            }
        }
        return result;
    }
}

这是DFS的解法

public class Solution {
    List<Integer> result = new ArrayList<Integer>();
    public List<Integer> rightSideView(TreeNode root) {
        dfs(root, 1);
        return result;
    }
    public void dfs(TreeNode root, int level) {
        if (root == null) {
            return;
        }
        if (result.size() < level) {
            result.add(root.val);
        }
        dfs(root.right, level + 1);
        dfs(root.left, level + 1);
    }
}

 

[LeetCode]Binary Tree Right Side View

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/5004665.html

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