Construct Binary Tree from Preorder and Inorder Traversal

題目:根據中序遍歷和前序遍歷數組構建二叉樹

解題思路:
比如 : pre = { A , B , D , E , C} in= {D , B , E , A , C}
1. A 爲root, 在中序遍歷中 , 找到左子樹節點爲D, B , E , 右子樹 : C
2. A左子樹根節點 = B , 同理找到它的左右子樹…
3. 如此遞歸

/**
 * Definition for a binary tree node.
 * 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.length == 0 || inorder.length == 0) return null;
        return build(preorder , 0 , preorder.length - 1 , inorder , 0 , inorder.length - 1);
    }

    public TreeNode build(int[] preorder , int ps , int pe , int[] inorder , int is , int ie ) {
        if(ps > pe) return null;

        TreeNode root = new TreeNode(preorder[ps]);
        int i = is;
        for(; i < inorder.length; i++) {
            if(inorder[i] == preorder[ps]) {
                break;
            }
        }

        root.left = build(preorder , ps+1 ,ps + i - is,inorder ,is ,i - 1);
        root.right = build(preorder,ps+i - is + 1 , pe, inorder , i+1 , ie);

        return root;
    }
}
發佈了121 篇原創文章 · 獲贊 2 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章