leetcode第44題(construct-binary-tree-from-preorder-and-inorder-……)

題目:

Given preorder and inorder traversal of a tree, construct the binary tree. 

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


思路:

前序遍歷是根左右,中序遍歷是左根右,第一個節點是跟,中序中根的左邊爲左子樹,根的右邊是右子樹,因而通過遞歸就可得到答案。

代碼:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder==null || preorder.length==0 || inorder==null || inorder.length==0){
            return null;
        }
        return constructTree(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
    }
    public TreeNode constructTree(int[] preorder,int prestart,int preend,int[] inorder,int instart,int inend){
        if(prestart>preend || instart>inend){
            return null;
        }
        TreeNode root = new TreeNode(preorder[prestart]);
        for(int i=0;i<preorder.length;i++){
            if(inorder[i] == preorder[prestart]){
                root.left = constructTree(preorder,prestart+1,prestart+i-instart,inorder,instart,i-1);
                root.right = constructTree(preorder,prestart+i-instart+1,preend,inorder,i+1,inend);
            }
        }
        return root;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章