首页 > 其他 > 详细

重建二叉树

时间:2021-06-06 00:49:59      阅读:28      评论:0      收藏:0      [点我收藏+]

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:

    3
   /   9  20
    /     15   7

思路

  • 前序遍历是先输出根节点,所以第一个元素一定是根节点
  • 中序遍历是先输出左边节点,在输出根节点,也就是在中序遍历中根节点左边的

由此可得:

  1. 根据前序遍历的根节点去中序遍历中找出对应值的位置。
  2. 在中序遍历该位置的左边是该节点左子树的节点,该位置右边是节点右子树的节点。
  3. 然后递归查找左子树和右子树的根节点并返回即可。

代码

class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return recursionBuildTree(preorder,inorder,0,preorder.length - 1);
    }
    int num = 0;
    public TreeNode  recursionBuildTree(int[] preorder, int[] inorder, int l, int r){
        if (l > r)
            return null;
        TreeNode root =  new TreeNode(preorder[num++]);
        if (l == r)
            return root;
        int i = l;
        for (; i <= r; i++) {
            if (inorder[i] == root.val)
                break;
        }
        root.left = recursionBuildTree(preorder,inorder, l, i-1);
        root.right = recursionBuildTree(preorder,inorder, i+1, r);
        return root;
    }

    public static void main(String[] args) {
        int []preorder = {3,9,20,15,7};
        int []inorder = {9,3,15,20,7};
        TreeNode root = new Solution().buildTree(preorder,inorder);
        System.out.println(root.val);
        System.out.println(root.left.val + "\t" + root.right.val);
        System.out.println(root.right.left.val + "\t" + root.right.right.val);

    }
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
}

重建二叉树

原文:https://www.cnblogs.com/chengejie/p/14854008.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!