Java实现 LeetCode 105 从前序与中序遍历序列构造二叉树

105. 从前序与中序遍历序列构造二叉树

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

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

    3
   / \
  9  20
    /  \
   15   7
 
class Solution {
     private int pre=0;
    private int in=0;
    public TreeNode buildTree(int [] preorder, int [] inorder) {
        return buildTree(preorder,inorder,Integer.MAX_VALUE+1);
    }
    public TreeNode buildTree(int [] preorder,int [] inorder,long stop){
        if(pre==preorder.length){
            return null;
        }
        //走到左下第一个值可返回
        if(inorder[in]==stop){
            in++;
            return null;
        }
        //一直往左下走
        int val=preorder[pre++];
        TreeNode root=new TreeNode(val);
        
        root.left=buildTree(preorder,inorder,val);
       // 其实往右走,就是返回之前的stop
        root.right=buildTree(preorder,inorder,stop);
        return root;
    }
}
发布了1221 篇原创文章 · 获赞 1万+ · 访问量 66万+

猜你喜欢

转载自blog.csdn.net/a1439775520/article/details/104379922