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

时间:2020-05-22
本文章向大家介绍[LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal,主要包括[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的结果分成左子树和右子树。照着例子解释一下,

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         // corner case
13         if (inorder == null || postorder == null || inorder.length == 0 || postorder.length == 0) {
14             return null;
15         }
16         return helper(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
17     }
18 
19     private TreeNode helper(int[] inorder, int inStart, int inEnd, int[] postorder, int pStart, int pEnd) {
20         // corner case
21         if (inStart > inEnd || pStart > pEnd) {
22             return null;
23         }
24         TreeNode root = new TreeNode(postorder[pEnd]);
25         int index = 0;
26         while (inorder[inStart + index] != postorder[pEnd]) {
27             index++;
28         }
29         root.left = helper(inorder, inStart, inStart + index - 1, postorder, pStart, pStart + index - 1);
30         root.right = helper(inorder, inStart + index + 1, inEnd, postorder, pStart + index, pEnd - 1);
31         return root;
32     }
33 }

相关题目

105. Construct Binary Tree from Preorder and Inorder Traversal

106. Construct Binary Tree from Inorder and Postorder Traversal

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12936155.html