[LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal

Posted CNoodle

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal相关的知识,希望对你有一定的参考价值。

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

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

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \\
  9  20
    /  \\
   15   7

从中序和后序遍历序列构造二叉树。

题目就是题意,影子题105,几乎一模一样

思路还是递归/分治。因为有了后序遍历所以后序遍历的最后一个 node 就是根节点。有了根节点,可以依据这个根节点在 inorder 遍历的位置,将 inorder 的结果分成左子树和右子树。代码中的 index 变量,找的是根节点在 inorder 里面的坐标。照着例子解释一下,

inorder = [9,3,15,20,7] - 9是左子树,15,20,7是右子树
postorder = [9,15,7,20,3] - 3是根节点

思路和代码可以参照105题,几乎是一样的。

时间O(n)

空间O(n)

Java实现

 1 /**
 2 * Definition for a binary tree node.
 3 * public class TreeNode {
 4 *     int val;
 5 *     TreeNode left;
 6 *     TreeNode right;
 7 *     TreeNode(int x) { val = x; }
 8 * }
 9 */
10 class Solution {
11     public TreeNode buildTree(int[] inorder, int[] postorder) {
12         return helper(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
13     }
14 
15     private TreeNode helper(int[] inorder, int inStart, int inEnd, int[] postorder, int pStart, int pEnd) {
16         // corner case
17         if (inStart > inEnd || pStart > pEnd) {
18             return null;
19         }
20         TreeNode root = new TreeNode(postorder[pEnd]);
21         // 找根节点在inorder的位置
22         int index = 0;
23         while (inorder[inStart + index] != postorder[pEnd]) {
24             index++;
25         }
26         root.left = helper(inorder, inStart, inStart + index - 1, postorder, pStart, pStart + index - 1);
27         root.right = helper(inorder, inStart + index + 1, inEnd, postorder, pStart + index, pEnd - 1);
28         return root;
29     }
30 }

 

相关题目

105. Construct Binary Tree from Preorder and Inorder Traversal

106. Construct Binary Tree from Inorder and Postorder Traversal

889. Construct Binary Tree from Preorder and Postorder Traversal

1008. Construct Binary Search Tree from Preorder Traversal

LeetCode 题目总结

以上是关于[LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal

LeetCode-106-Construct Binary Tree from Inorder and Postorder Traversal

leetcode 106 Construct Binary Tree from Inorder and Postorder Traversal----- java

LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal

LeetCode-面试算法经典-Java实现106-Construct Binary Tree from Inorder and Postorder Traversal(构造二叉树II)(示例(代码片

[LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和后序遍历建立二叉树