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;
    }
}
相關文章
相關標籤/搜索