算法:二叉树从右侧看到的内容 199. Binary Tree Right Side View
Posted 架构师易筋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法:二叉树从右侧看到的内容 199. Binary Tree Right Side View相关的知识,希望对你有一定的参考价值。
199. Binary Tree Right Side View
Given the root of 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:
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Example 2:
Input: root = [1,null,3]
Output: [1,3]
Example 3:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
DFS深度优先解法
从右侧看过来,如果只有左侧,因为右侧为空,所以也能看到左侧。
1
/
2
/
3
比如上面的结果,应该是1,2,3. 所以问题转换为每一层只存一个数,从右节点开始遍历。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> list = new ArrayList<>();
dfs(root, list, 0);
return list;
}
private void dfs(TreeNode root, List<Integer> list, int layer) {
if (root == null) return;
if (list.size() == layer)
list.add(root.val);
dfs(root.right, list, layer + 1);
dfs(root.left, list, layer + 1);
}
}
以上是关于算法:二叉树从右侧看到的内容 199. Binary Tree Right Side View的主要内容,如果未能解决你的问题,请参考以下文章