• 199. 二叉树的右视图-二叉树,dfs,从右往左遍历-中等难度


    问题描述

    给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

    示例:

    输入: [1,2,3,null,5,null,4]
    输出: [1, 3, 4]
    解释:

    1 <---
    /
    2 3 <---

    5 4 <---

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/binary-tree-right-side-view

    解答

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    '''
    
    不同于往常的dfs,这次我们从右边开始遍历二叉树。
    
    '''
    class Solution(object):
        def rightSideView(self, root):
            if root == None:
                return []
            now = [0,0]
            result = [root.val]
            def dfs(root):
                if root.left == None and root.right == None:
                    return
                if root.right != None:
                    now[0] += 1
                    if now[0] >= now[1]+1:
                        now[1] += 1
                        result.append(root.right.val)
                    dfs(root.right)
                    now[0] -= 1
                if root.left != None:
                    now[0] += 1
                    if now[0] >= now[1]+1:
                        now[1] += 1
                        result.append(root.left.val)
                    dfs(root.left)
                    now[0] -= 1
            dfs(root)
            return result

  • 相关阅读:
    算符优先分析
    自下而上语法分析
    递归下降语法分析
    LL(1)文法的判断,递归下降分析程序
    消除左递归
    4.K均值算法--应用
    2.机器学习相关数学基础
    K均值算法
    机器学习概述
    算符优先分析
  • 原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13250821.html
Copyright © 2020-2023  润新知