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

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
posted @ 2016-05-25 23:12  absolute100  阅读(119)  评论(0编辑  收藏  举报