Binary Tree Right Side View

题目: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.

解题思路:
1. 右子树的高度 >= 左子树 , easy ;
2. 左子树 > 右子树?
3. 通过层序遍历(BFS),每一层的最右边加入结果链表;

/**
 * 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> list = new ArrayList<Integer> ();
        LinkedList<TreeNode> queue = new LinkedList<TreeNode> ();
        //当前层节点个数,下一层节点个数
        int curCount , nextCount = 0;
        if(root == null) return list;
        queue.add(root);
        curCount = 1;
        list.add(root.val);

        while(!queue.isEmpty()) {
            if(curCount == 0) {
                curCount = nextCount;
                // 注意这里一定要置0
                nextCount = 0;
                list.add(queue.getLast().val);
            }
            TreeNode node = queue.removeFirst();
            curCount--;
            if(node.left != null) {
                queue.add(node.left);
                nextCount++;
            }
            if(node.right != null) {
                queue.add(node.right);
                nextCount++;
            }
        }

        return list;
    }
}

DFS(前序遍历)解题

  • 因为每一层都必然有一个会有一个值添加到返回链表中;
  • 这样我们只要比较返回链表的大小与当前的深度,如果小于,则添加到链表
public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> result = new ArrayList<Integer>();
            help(root, 1, result);
            return result;
        }

        public void help(TreeNode root, int depth, List<Integer> result) {
            if (root == null)
                return;
            if (result.size() < depth)
                result.add(root.val);
            // 从右子树开始!
            help(root.right, depth + 1, result);
            help(root.left, depth + 1, result);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值