问题描述
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [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