输出二叉树的右视图

日常看不懂系列

  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;

   }


全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
正在热议
更多
# 春招至今,你的战绩如何? #
9842次浏览 92人参与
# 你的实习产出是真实的还是包装的? #
1768次浏览 41人参与
# 米连集团26产品管培生项目 #
5783次浏览 214人参与
# 军工所铁饭碗 vs 互联网高薪资,你会选谁 #
7489次浏览 43人参与
# 简历第一个项目做什么 #
31584次浏览 331人参与
# 重来一次,我还会选择这个专业吗 #
433389次浏览 3926人参与
# 巨人网络春招 #
11305次浏览 223人参与
# 当下环境,你会继续卷互联网,还是看其他行业机会 #
187019次浏览 1122人参与
# 牛客AI文生图 #
21411次浏览 238人参与
# 不考虑薪资和职业,你最想做什么工作呢? #
152303次浏览 887人参与
# 研究所笔面经互助 #
118877次浏览 577人参与
# 简历中的项目经历要怎么写? #
310102次浏览 4195人参与
# AI时代,哪些岗位最容易被淘汰 #
63464次浏览 805人参与
# 面试紧张时你会有什么表现? #
30490次浏览 188人参与
# 你今年的平均薪资是多少? #
213027次浏览 1039人参与
# 你怎么看待AI面试 #
179897次浏览 1237人参与
# 高学历就一定能找到好工作吗? #
64317次浏览 620人参与
# 你最满意的offer薪资是哪家公司? #
76446次浏览 374人参与
# 我的求职精神状态 #
448005次浏览 3129人参与
# 正在春招的你,也参与了去年秋招吗? #
363287次浏览 2637人参与
# 腾讯音乐求职进展汇总 #
160598次浏览 1111人参与
# 校招笔试 #
470549次浏览 2964人参与
牛客网
牛客网在线编程
牛客网题解
牛客企业服务