输出二叉树的右视图

输出二叉树的右视图

https://www.nowcoder.com/practice/c9480213597e45f4807880c763ddd5f0?tpId=117&tqId=37848&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fjob-code-high%2Fquestion-ranking&tab=answerKey

//分两步,第一步重建二叉树,第二步,层序遍历二叉树,取每一层最右边的节点即为右视图

public int[] solve (int[] xianxu, int[] zhongxu) {
        // write code here
        TreeNode root = reBuild(xianxu,0,xianxu.length-1,zhongxu,0,
                               zhongxu.length-1);
        int[] res = cenxu(root);
        return res;
    }
    private int[] cenxu(TreeNode root){
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        List<Integer> res = new ArrayList<>();
        while(queue.size()>0){
            int len = queue.size();
            for(int i=1;i<=len;i++){
                TreeNode tn = queue.poll();
                if(tn.left!=null) queue.add(tn.left);
                if(tn.right!=null) queue.add(tn.right);
                if(i==len) res.add(tn.val);
            }
        }
        int[] r = new int[res.size()];
        int y = 0;
        for(int a:res){
            r[y++] = a;
        }
        return r;
    }
    private TreeNode reBuild(int[] xianxu,int xbegin,int xend,int[] zhongxu,
                            int zbegin,int zend){
        if(xbegin>xend || zbegin > zend) return null;
        if(xbegin==xend) return new TreeNode(xianxu[xbegin]);
        int temp = xianxu[xbegin];
        int index = 0;
        for(int i=zbegin;i<=zend;i++){
            if(zhongxu[i]==temp){
                index = i;
                break;
            }
        }
        //zhongxu    zbegin - index-1                   index+1 - zend
        //xianxu     xbegin+1 - xbegin+index-zbegin      xbegin+index-zbegin+1-- xend
        TreeNode left = reBuild(xianxu,xbegin+1,xbegin+index-zbegin,zhongxu,zbegin,index-1);
        TreeNode right = reBuild(xianxu,xbegin+index-zbegin+1,xend,zhongxu,index+1,zend);
        TreeNode root = new TreeNode(temp);
        root.left = left;
        root.right = right;
        return root;
    }
全部评论

相关推荐

10-13 17:47
门头沟学院 Java
wulala.god:图一那个善我面过,老板网上找的题库面的
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务