Construct Binary Tree from Preorder and Inorder Traversal

Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.post

Note:
You may assume that duplicates do not exist in the tree.ui

1.解题思路
利用递归思想,先序遍历的第一个元素就是根节点,而后在中序遍历中寻找该节点,该节点左边的就是左子树,右边的是右子树。code

2.代码递归

public class Solution {
    int curroot=0;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
       return  build(0,inorder.length-1,preorder,inorder);
    }
    private TreeNode build(int instart,int inend,int[] preorder, int[] inorder){
        if(curroot==preorder.length||instart>inend) return null;
        TreeNode root=new TreeNode(preorder[curroot]);
        //find mid in inorder;
        int mid=0;
        for(int i=instart;i<=inend;i++){
            if(inorder[i]==preorder[curroot]){
                mid=i;
                break;
            }
                
        }
        curroot++;
        root.left=build(instart,mid-1,preorder,inorder);
        root.right=build(mid+1,inend,preorder,inorder);
        return root;
    }
}

Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.io

Note:
You may assume that duplicates do not exist in the tree.class

  1. 解题思路
    后序遍历,因此逻辑和上一题同样,可是咱们要从后序遍历的最后一个节点开始,这样咱们就得先处理右子树,再处理左子树。rsa

2.代码遍历

public class Solution {
    int curroot=0;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        curroot=postorder.length-1;
        return  build(0,inorder.length-1,inorder,postorder);
    }
    private TreeNode build(int instart,int inend,int[] inorder, int[] postorder){
        if(curroot<0||instart>inend) return null;
        TreeNode root=new TreeNode(postorder[curroot]);
        int mid=0;
        for(int i=instart;i<=inend;i++){
            if(inorder[i]==postorder[curroot]){
                mid=i;
                break;
            }
                
        }
        curroot--;
        root.right=build(mid+1,inend,inorder,postorder);
        root.left=build(instart,mid-1,inorder,postorder);
        
        return root;
    }
}
相关文章
相关标签/搜索