leetcode-199-二叉树的右视图

时间:2019-07-20
本文章向大家介绍leetcode-199-二叉树的右视图,主要包括leetcode-199-二叉树的右视图使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目描述:

第一次提交:

# 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]
        """
        if not root:
            return []
        stack = [root]
        res = []
        while stack:
            temp = []
            res.append(stack[0].val)
            for i in stack:
                if i.right:
                    temp.append(i.right)
                if i.left:
                    temp.append(i.left)
            stack = temp
        return res
            

方法二:

class Solution(object):
    def rightSideView(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        d={} 
        def f(r,i): 
            if r: 
                d[i]=r.val 
                f(r.left,i+1) 
                f(r.right,i+1) 
        f(root,0) 
        return list(d.values())

原文地址:https://www.cnblogs.com/oldby/p/11219246.html