边工作边刷题:70天一遍leetcode: day 3

本文深入探讨了BinaryTreeRightSideView算法中容易出现的错误,特别是关于遍历左右子树的顺序和判断节点可见性的逻辑。通过实例分析,详细解释了如何正确实现该算法以获取从上到下可见的右子树节点值。

Binary Tree Right Side View

错误点:

  • 是if right... if left,而不是if right elif left,因为有可能右子树向下没有左子树深,所以要左子树也遍历。而控制是否是第一个用的是结果list是否已经有元素。这里容易出错是因为会错认为如果有right child那么left child就不用考虑了,没有考虑之后的情况。

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


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def rightSideView(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        def doRight(root, depth, res):
            if depth==len(res):
                res.append(root.val)
            
            if root.right:
                doRight(root.right, depth+1, res)
            
            if root.left:
                doRight(root.left, depth+1, res)
            
        res = []
        if not root: return res
        doRight(root, 0, res)
        return res

转载于:https://www.cnblogs.com/absolute/p/5544322.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值