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

Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.

Example 1:

Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]

Example 2:

Input: inorder = [-1], postorder = [-1]
Output: [-1]

Constraints:

  • 1 <= inorder.length <= 3000
  • postorder.length == inorder.length
  • -3000 <= inorder[i], postorder[i] <= 3000
  • inorder and postorder consist of unique values.
  • Each value of postorder also appears in inorder.
  • inorder is guaranteed to be the inorder traversal of the tree.
  • postorder is guaranteed to be the postorder traversal of the tree.

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

给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目就是题意,影子题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 题目总结

posted @ 2020-05-22 11:30  CNoodle  阅读(570)  评论(0编辑  收藏  举报