leetcode 199. Binary Tree Right Side View-树的右视图|递归|非递归|Java|Python

本文介绍了一种求解二叉树右视图的算法,包括非递归层次遍历和递归前序遍历两种实现方式。通过这两种方法可以高效地获取二叉树每层最右侧节点的值。
 原题链接:199. Binary Tree Right Side View

【思路】非递归实现

层次遍历,每一层都是从左到右遍历,将每一层的最右一个节点添加到结果集中就是我们需要得到的结果:

public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) return res;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int n = queue.size();
            while(n-- > 0) {
                root = queue.poll();
                if(root.left != null) queue.add(root.left);
                if(root.right != null) queue.add(root.right);
                if(n == 0) res.add(root.val);  //将该层的最右一个节点添加到结果集中
            }
        }
        return res;
    }
}
210 / 210  test cases passed. Runtime: 2 ms  Your runtime beats 47.48% of javasubmissions.


import Queue
class Solution(object):
    def rightSideView(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root == None : return []
        queue, res = Queue.Queue(),[]
        queue.put(root)
        while not queue.empty() :
            n = queue.qsize()
            while (n > 0) :
                root = queue.get()
                if root.left : queue.put(root.left)
                if root.right : queue.put(root.right)
                if n == 1 : res.append(root.val)
                n -= 1
        return res
210 / 210  test cases passed. Runtime: 68 ms  Your runtime beats 15.41% of pythonsubmissions.

【思路】递归实现

采用前序遍历。采用 根->右->左 顺序进行遍历,并将每一层的第一个节点添加到结果集中:

public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        dfs(root, res, 0);
        return res;
    }
    private void dfs(TreeNode root, List<Integer> res, int level) {
        if (root == null) return;
        if (level == res.size()) {
            res.add(root.val);
        }
        dfs(root.right, res, level+1);
        dfs(root.left, res, level+1);
    }
}
210 / 210  test cases passed. Runtime: 1 ms  Your runtime beats 84.55% of javasubmissions.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值