友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

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

解题分析

使用递归,从底层向上构建整个树。

0106 01
0106 02

参考资料

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
 * Runtime: 0 ms, faster than 100.00% of Java online submissions for Construct Binary Tree from Inorder and Postorder Traversal.
 * Memory Usage: 41.3 MB, less than 14.54% of Java online submissions for Construct Binary Tree from Inorder and Postorder Traversal.
 */
public TreeNode buildTree(int[] inorder, int[] postorder) {
    return buildTree(inorder, postorder, 0, inorder.length - 1, postorder.length - 1);
}

private TreeNode buildTree(int[] inorder, int[] postorder, int instart, int inend, int postend) {
    if (postend < 0 || instart > inend) {
        return null;
    }
    int val = postorder[postend];
    int index = inend;
    for (; index >= instart; index--) {
        if (inorder[index] == val) {
            break;
        }
    }
    TreeNode result = new TreeNode(val);
    result.left = buildTree(inorder, postorder, instart, index - 1, postend - (inend - index) - 1);
    result.right = buildTree(inorder, postorder, index + 1, inend, postend - 1);
    return result;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 *在自己实现的基础上,参考: https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/solutions/426738/cong-zhong-xu-yu-hou-xu-bian-li-xu-lie-gou-zao-14/comments/2236345 解决了下标错误的问题。
 */
public TreeNode buildTree(int[] inorder, int[] postorder) {
  if (inorder == null || postorder == null || inorder.length != postorder.length) {
    return null;
  }
  Map<Integer, Integer> numToIndex = new HashMap<>();
  for (int i = 0; i < inorder.length; i++) {
    numToIndex.put(inorder[i], i);
  }
  return buildTree(inorder, postorder, numToIndex, 0, inorder.length - 1, 0, postorder.length - 1);
}

private TreeNode buildTree(int[] inorder, int[] postorder, Map<Integer, Integer> numToIndex, int inStart, int inEnd, int postStart, int postEnd) {
  if (inStart > inEnd || postStart > postEnd) {
    return null;
  }
  int value = postorder[postEnd];
  TreeNode root = new TreeNode(value);
  int index = numToIndex.get(value);
  int size = index - inStart;
  root.left = buildTree(inorder, postorder, numToIndex, inStart, index - 1, postStart, postStart + size - 1);
  root.right = buildTree(inorder, postorder, numToIndex, index + 1, inEnd, postStart + size, postEnd - 1);
  return root;
}
0106 03