题解 | #输出二叉树的右视图#递归生成二叉树加上层序遍历生成右视图

输出二叉树的右视图

http://www.nowcoder.com/practice/c9480213597e45f4807880c763ddd5f0

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 求二叉树的右视图
     * @param xianxu int整型一维数组 先序遍历
     * @param zhongxu int整型一维数组 中序遍历
     * @return int整型一维数组
     */
    public int[] solve(int[] xianxu, int[] zhongxu) {
        // write code here
        TreeNode root = buildertree(xianxu, 0, xianxu.length - 1, zhongxu, 0, zhongxu.length - 1);
        int[] result = helper(root);

        return result;
    }

    private int[] helper(TreeNode root) {

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        ArrayList<Integer> list = new ArrayList<>();
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (size == 1) {
                    list.add(node.val);
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                size--;
            }

        }
        int[] result = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            result[i] = list.get(i);
        }
        return result;
    }

    private TreeNode buildertree(int[] preorder, int preleft, int preright, int[] inorder, int inleft, int inright) {
        if (preleft > preright) {
            return null;
        }
        int rootval = preorder[preleft];
        TreeNode root = new TreeNode(rootval);
        int rootIndex = 0;
        for (int i = 0; i < inorder.length; i++) {
            if (inorder[i] == rootval) {
                rootIndex = i;
                break;
            }
        }

        root.left = buildertree(preorder, preleft + 1, preleft + (rootIndex - inleft), inorder, inleft, rootIndex - 1);
        root.right = buildertree(preorder, preleft + (rootIndex - inleft) + 1, preright, inorder, rootIndex + 1, inright);

        return root;
    }
}
全部评论

相关推荐

HNU_fsq:建议直接出国,这简历太6了。自愧不如
点赞 评论 收藏
分享
牛客101244697号:这个衣服和发型不去投偶像练习生?
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务