输出二叉树的右视图
日常看不懂系列
public TreeNode buildTree(int[] xianxu,int l1,int r1,int[] zhongxu,int l2,int r2){
if(l1>r1||l2>r2){
return null;
}
TreeNode root=new TreeNode(xianxu[l1]);
int rootIndex=0;
for (int i=l2;i<=r2;i++){
if(zhongxu[i]==xianxu[l1]){
rootIndex=i;
break;
}
}
int leftsize=rootIndex-l2;
int rightsize=r2-rootIndex;
root.left=buildTree(xianxu,l1+1,l1+leftsize,zhongxu,l2,l2+leftsize-1);
root.right=buildTree(xianxu,r1-rightsize+1,r1,zhongxu,rootIndex+1,r2);
return root;
}
public ArrayList<Integer> rightSideView(TreeNode root){
Map<Integer,Integer> mp=new HashMap<Integer,Integer>();
int max_depth=-1;
Stack<TreeNode> nodes=new Stack<TreeNode>();
Stack<Integer> depths=new Stack<Integer>();
nodes.push(root);
depths.push(0);
while (!nodes.isEmpty()){
TreeNode node=nodes.pop();
int depth=depths.pop();
if(node!=null){
max_depth=Math.max(max_depth,depth);
if(mp.get(depth)==null) mp.put(depth,node.val);
nodes.push(node.left);
nodes.push(node.right);
depths.push(depth+1);
depths.push(depth+1);
}
}
ArrayList<Integer> res=new ArrayList<Integer>();
for (int i=0;i<=max_depth;i++){
res.add(mp.get(i));
}
return res;
}
public int[] solve(int[] xianxu,int[] zhongxu){
if(xianxu.length==0) return new int[0];
TreeNode root=buildTree(xianxu,0,xianxu.length-1,zhongxu,0,zhongxu.length-1);
ArrayList<Integer> temp=rightSideView(root);
int[] res=new int[temp.size()];
for (int i=0;i< temp.size();i++){
res[i]=temp.get(i);
}
return res;
}