1. 程式人生 > >【LeetCode-面試算法經典-Java實現】【106-Construct Binary Tree from Inorder and Postorder Traversal(構造二叉樹II)】

【LeetCode-面試算法經典-Java實現】【106-Construct Binary Tree from Inorder and Postorder Traversal(構造二叉樹II)】

struct ons node dcl 實現 ftl rsa tor var

【106-Construct Binary Tree from Inorder and Postorder Traversal(通過中序和後序遍歷構造二叉樹)】


【LeetCode-面試算法經典-Java實現】【全部題目文件夾索引】

原題

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

題目大意

  給定一個中序遍歷和後序遍歷序列,構造一棵二叉樹
  註意:


  樹中沒有反復元素

解題思路

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

代碼實現

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

算法實現類

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; } }

評測結果

  點擊圖片,鼠標不釋放。拖動一段位置,釋放後在新的窗體中查看完整圖片。

技術分享

特別說明

歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47371993】

【LeetCode-面試算法經典-Java實現】【106-Construct Binary Tree from Inorder and Postorder Traversal(構造二叉樹II)】