LintCode-73. 前序遍歷和中序遍歷樹構(gòu)造二叉樹

題目

描述

根據(jù)前序遍歷和中序遍歷樹構(gòu)造二叉樹.

樣例

樣例 1:
    輸入:  in-order = [], pre-order = []
    輸出: null  


樣例 2:
    輸入: in-order = [1,2,3], pre-order = [2,1,3]
    輸出:  
    
      2
     / \
    1   3

注意事項

你可以假設樹中不存在相同數(shù)值的節(jié)點

解答

思路

根據(jù)注意事項,前序遍歷的節(jié)點從根節(jié)點開始,那么在中序遍歷中對應的節(jié)點的左邊就是其左子樹,右邊就是其右子樹了。

代碼

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param inorder: A list of integers that inorder traversal of a tree
     * @param postorder: A list of integers that postorder traversal of a tree
     * @return: Root of a tree
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        // write your code here
        if (preorder.length == 0 && inorder.length == 0) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[0]);
        int length = inorder.length;
        int rootIndex = 0;
        for (int a : inorder) {
            if (a == preorder[0]) {
                break;
            }
            rootIndex++;
        }
        root.left = buildTree(java.util.Arrays.copyOfRange(preorder, 1, 1 + rootIndex), java.util.Arrays.copyOfRange(inorder, 0, rootIndex));
        root.right = buildTree(java.util.Arrays.copyOfRange(preorder, rootIndex + 1, length), java.util.Arrays.copyOfRange(inorder, rootIndex + 1, length));
        return root;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容