描述
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.
Example:
1 2 3 4 5 6 7 8 9
| Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation:
1 <--- / \ 2 3 <--- \ \ 5 4 <---
|
分析
广度优先遍历,拿 515. Find Largest Value in Each Tree Row 的代码改了两行就 AC 了。
解决方案1(Python)
深度优先搜索,因为每次压栈然后出栈,会先访问右子树,对于每一层来说,见到的都是最右边的节点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rightSideView(self, root: Optional[TreeNode]) -> List[int]: depthValueMap = dict() maxDepth = -1 stack = [(root, 0)] while stack: node, depth = stack.pop() if node is not None: maxDepth = max(maxDepth, depth) depthValueMap.setdefault(depth, node.val) stack.append((node.left, depth+1)) stack.append((node.right, depth+1)) return [depthValueMap[depth] for depth in range(maxDepth+1)]
|
解决方案1(Java)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new LinkedList<>(); if (root == null) { return result; } Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int nowRightNode = Integer.MIN_VALUE, size = queue.size(); while(!queue.isEmpty()) { size = queue.size(); for (int i = 0; i < size; i++) { TreeNode nowNode = queue.poll(); if (i == size-1) { nowRightNode = nowNode.val; } if (nowNode.left != null) { queue.offer(nowNode.left); } if (nowNode.right != null) { queue.offer(nowNode.right); } } result.add(nowRightNode); } return result; } }
|
解决方案2(golang)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
func rightSideView(root *TreeNode) []int { if root == nil { return []int{} } result := []int{} queue := make([]*TreeNode, 0) queue = append(queue, root) for len(queue) > 0 { length := len(queue) result = append(result, queue[length-1].Val) for i := 0; i < length; i++ { node := queue[0] queue = queue[1:] if node.Left != nil { queue = append(queue, node.Left) } if node.Right != nil { queue = append(queue, node.Right) } } } return result }
|
相关问题