Question

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.

For example:
Given the following binary tree,

1 <—
/ \
2 3 <—
\ \
5 4 <—

You should return ​​[1, 3, 4]​​.


本题难度Medium。有2种算法分别是: DFS 和 层序遍历

题意

将二叉树每层的最右边节点值由上而下依次排列出来

1、DFS

复杂度

时间 O(2^h-1) 空间 O(h) 递归栈空间

思路

我们用DFS,优先遍历右子树并记录遍历的深度,如果这个右子节点的深度大于当前所记录的最大深度(全局变量),说明它是下一层的最右节点,将其加入结果中。

[LeetCode]Binary Tree Right Side View_List

这里的dfs函数没有base case,因为base case已经融入到判断该节点是否为​​null​​中(第24、25行)

代码

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int maxDepth=0;
public List<Integer> rightSideView(TreeNode root) {
//require
List<Integer> ans=new LinkedList<>();
if(root!=null)dfs(1,root,ans);
//ensure
return ans;
}
private void dfs(int depth,TreeNode root,List<Integer> ans){
if(depth>maxDepth){
maxDepth=depth;
ans.add(root.val);
}
if(root.right!=null)dfs(depth+1,root.right,ans);
if(root.left!=null)dfs(depth+1,root.left,ans);
}
}

2、层序遍历

复杂度

时间 O(2^h-1) 空间 O(2^(h-1))

思路

利用层序遍历,只要把每层的最后一个取出放入结果即可。

代码

public class Solution {
private int maxDepth=0;
public List<Integer> rightSideView(TreeNode root) {
//require
List<Integer> ans=new LinkedList<>();
Queue<TreeNode> q=new LinkedList<>();
//invariant
if(root!=null)q.offer(root);
level(q,ans);
//ensure
return ans;
}
private void level(Queue<TreeNode> q,List<Integer> ans){
//base case
if(q.isEmpty())return;

Queue<TreeNode> nextQ=new LinkedList<>();
ans.add(q.peek().val);//record the rightest node
while(!q.isEmpty()){
TreeNode n=q.poll();
if(n.right!=null)nextQ.offer(n.right);
if(n.left!=null)nextQ.offer(n.left);
}
level(nextQ,ans);
}
}