經過中序和後序遍歷構造二叉樹

原題

  Given inorder and postorder traversal of a tree, construct the binary tree.
  Note:
  You may assume that duplicates do not exist in the tree.算法

題目大意

  給定一箇中序遍歷和後序遍歷序列,構造一棵二叉樹
  注意:
  樹中沒有重複元素post

解題思路

  後序遍歷的最後一個元素就是樹的根結點(值爲r),在中序遍歷的序列中找值爲r的位置idx,idx將中序遍歷序列分爲左右兩個子樹,對應能夠將後序遍歷的序列分在兩個子樹,遞歸對其進行求解。ui

代碼實現

 

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

 

算法實現類spa

public class Solution {

    public TreeNode buildTree(int[] inorder, int[] postorder) {

        // 參數檢驗
        if (inorder == null || postorder == null || inorder.length == 0
                || inorder.length != postorder.length) {
            return null;
        }

        // 構建二叉樹
        return solve(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }

    /**
     * 構建二叉樹
     *
     * @param inorder   中序遍歷的結果
     * @param x         中序遍歷的開始位置
     * @param y         中序遍歷的結束位置
     * @param postorder 後序遍歷的結果
     * @param i         後序遍歷的開始位置
     * @param j         後序遍歷的結束位置
     * @return 二叉樹
     */
    public TreeNode solve(int[] inorder, int x, int y, int[] postorder, int i, int j) {

        if (x >= 0 && x <= y && i >= 0 && i <= j) {
            // 只有一個元素,(此時也有i=j成)
            if (x == y) {
                return new TreeNode(postorder[j]);
            }
            // 多於一個元素,此時也有i<j
            else if (x < y) {
                // 建立根結點
                TreeNode root = new TreeNode(postorder[j]);

                // 找根結點在中序遍歷的下標
                int idx = x;
                while (idx < y && inorder[idx] != postorder[j]) {
                    idx++;
                }

                // 左子樹非空,構建左子樹
                int leftLength = idx - x;
                if (leftLength > 0) {
                    // i, i + leftLength - 1,前序遍歷的左子樹的起始,結束位置
                    root.left = solve(inorder, x, idx - 1, postorder, i, i + leftLength - 1);
                }

                // 右子樹非空,構建右子樹
                int rightLength = y - idx;
                if (rightLength > 0) {
                    // i + leftLength, j - 1,前序遍歷的右子樹的起始,結束位置
                    root.right = solve(inorder, idx + 1, y, postorder, i + leftLength, j - 1);
                }

                return root;
            } else {
                return null;
            }
        }

        return null;
    }
}
相關文章
相關標籤/搜索