[编程题] JZ4 重建二叉树

[编程题] JZ4 重建二叉树

image-20200725162319558

参考

参考讲解

思路

我们根据前序遍历的首节点就指定二叉树的根,我们在中序遍历中查找这个根,就可以把中序遍历分为两部分,即左子树和右子树。那么,我们知道了左子树的长度,我们也可以在前序遍历中知道前序遍历中左子树的数组范围。此时:

  • 我们知道了前序遍历中的左子树的子数组,我们知道了中序遍历中的左子树的子数组,可以拿这个进行左递归。
  • 我们知道了前序遍历中的右子树的子数组,我们知道了中序遍历中的右子树的子数组,可以拿这个进行右递归。

image-20200725162739032

代码

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        TreeNode res = help(pre,in,0,pre.length-1,0,in.length-1);
        return res;
    }
    
    public TreeNode help(int[] pre,int[] in,int preLeft,int preRight,int inLeft,int inRight){
        //极端条件
        if(preLeft>pre.length || inLeft>in.length || preLeft>preRight || inLeft>inRight){
            return null;
        }

        //标记当前跟节点
        int value = pre[preLeft];
        TreeNode node = new TreeNode(value);
        
        int count = inLeft;
        while(in[count]!=value){
            count++;
        }
        count = count-inLeft;//确定左子树的长度

        //建造左子树并递归
        node.left = help(pre,in,preLeft+1,preLeft+count,inLeft,inLeft+count-1);
        //建造右子树并递归
        node.right = help(pre,in,preLeft+count+1,preRight,inLeft+count+1,inRight);
        return node;
    }
}
posted @ 2020-07-25 16:29  北鼻coder  阅读(180)  评论(0编辑  收藏  举报