Description
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:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <—
/
2 3 <—
\
5 4 <—
Solution
给一棵二叉树,返回这棵二叉树从右边看的从root到leaf的值。
We use an int depth to document the depth of we have travered. If depth is equal to size of res. We add the node’s value into res. It is kind like post order traversal. node->right-left order.
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
rightViewHelper(res, root, 0);
return res;
}
private void rightViewHelper(List<Integer> res, TreeNode node, int depth){
if (node == null){
return;
}
if (depth == res.size()){
res.add(node.val);
}
rightViewHelper(res, node.right, depth + 1);
rightViewHelper(res, node.left, depth + 1);
}
}
Time Complexity: O()
Space Complexity: O()

本文深入探讨了二叉树右视图算法的实现原理,通过递归方式记录每一层最右侧节点的值,从顶部到底部展示二叉树的右侧面。算法采用类似于后序遍历的方式,先右子树后左子树,确保每层的最后一个节点被记录。
548

被折叠的 条评论
为什么被折叠?



