返回介绍

solution / 0100-0199 / 0106.Construct Binary Tree from Inorder and Postorder Traversal / README_EN

发布于 2024-06-17 01:04:05 字数 8945 浏览 0 评论 0 收藏 0

106. Construct Binary Tree from Inorder and Postorder Traversal

中文文档

Description

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.

Solutions

Solution 1: Hash Table + Recursion

The last node in the post-order traversal is the root node. We can find the position of the root node in the in-order traversal, and then recursively construct the left and right subtrees.

Specifically, we first use a hash table $d$ to store the position of each node in the in-order traversal. Then we design a recursive function $dfs(i, j, n)$, where $i$ and $j$ represent the starting positions of the in-order and post-order traversals, respectively, and $n$ represents the number of nodes in the subtree. The function logic is as follows:

  • If $n \leq 0$, it means the subtree is empty, return a null node.
  • Otherwise, take out the last node $v$ of the post-order traversal, and then find the position $k$ of $v$ in the in-order traversal using the hash table $d$. Then the number of nodes in the left subtree is $k - i$, and the number of nodes in the right subtree is $n - k + i - 1$.
  • Recursively construct the left subtree $dfs(i, j, k - i)$ and the right subtree $dfs(k + 1, j + k - i, n - k + i - 1)$, connect them to the root node, and finally return the root node.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.

# Definition for a binary tree node.
# class TreeNode:
#   def __init__(self, val=0, left=None, right=None):
#     self.val = val
#     self.left = left
#     self.right = right
class Solution:
  def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
    def dfs(i: int, j: int, n: int) -> Optional[TreeNode]:
      if n <= 0:
        return None
      v = postorder[j + n - 1]
      k = d[v]
      l = dfs(i, j, k - i)
      r = dfs(k + 1, j + k - i, n - k + i - 1)
      return TreeNode(v, l, r)

    d = {v: i for i, v in enumerate(inorder)}
    return dfs(0, 0, len(inorder))
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *   int val;
 *   TreeNode left;
 *   TreeNode right;
 *   TreeNode() {}
 *   TreeNode(int val) { this.val = val; }
 *   TreeNode(int val, TreeNode left, TreeNode right) {
 *     this.val = val;
 *     this.left = left;
 *     this.right = right;
 *   }
 * }
 */
class Solution {
  private Map<Integer, Integer> d = new HashMap<>();
  private int[] postorder;

  public TreeNode buildTree(int[] inorder, int[] postorder) {
    this.postorder = postorder;
    int n = inorder.length;
    for (int i = 0; i < n; ++i) {
      d.put(inorder[i], i);
    }
    return dfs(0, 0, n);
  }

  private TreeNode dfs(int i, int j, int n) {
    if (n <= 0) {
      return null;
    }
    int v = postorder[j + n - 1];
    int k = d.get(v);
    TreeNode l = dfs(i, j, k - i);
    TreeNode r = dfs(k + 1, j + k - i, n - k + i - 1);
    return new TreeNode(v, l, r);
  }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *   int val;
 *   TreeNode *left;
 *   TreeNode *right;
 *   TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *   TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *   TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
  TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
    unordered_map<int, int> d;
    int n = inorder.size();
    for (int i = 0; i < n; ++i) {
      d[inorder[i]] = i;
    }
    function<TreeNode*(int, int, int)> dfs = [&](int i, int j, int n) -> TreeNode* {
      if (n <= 0) {
        return nullptr;
      }
      int v = postorder[j + n - 1];
      int k = d[v];
      auto l = dfs(i, j, k - i);
      auto r = dfs(k + 1, j + k - i, n - k + i - 1);
      return new TreeNode(v, l, r);
    };
    return dfs(0, 0, n);
  }
};
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */
func buildTree(inorder []int, postorder []int) *TreeNode {
  d := map[int]int{}
  for i, v := range inorder {
    d[v] = i
  }
  var dfs func(i, j, n int) *TreeNode
  dfs = func(i, j, n int) *TreeNode {
    if n <= 0 {
      return nil
    }
    v := postorder[j+n-1]
    k := d[v]
    l := dfs(i, j, k-i)
    r := dfs(k+1, j+k-i, n-k+i-1)
    return &TreeNode{v, l, r}
  }
  return dfs(0, 0, len(inorder))
}
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *   val: number
 *   left: TreeNode | null
 *   right: TreeNode | null
 *   constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 *   }
 * }
 */

function buildTree(inorder: number[], postorder: number[]): TreeNode | null {
  const n = inorder.length;
  const d: Record<number, number> = {};
  for (let i = 0; i < n; i++) {
    d[inorder[i]] = i;
  }
  const dfs = (i: number, j: number, n: number): TreeNode | null => {
    if (n <= 0) {
      return null;
    }
    const v = postorder[j + n - 1];
    const k = d[v];
    const l = dfs(i, j, k - i);
    const r = dfs(k + 1, j + k - i, n - 1 - (k - i));
    return new TreeNode(v, l, r);
  };
  return dfs(0, 0, n);
}
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//   TreeNode {
//     val,
//     left: None,
//     right: None
//   }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
impl Solution {
  pub fn build_tree(inorder: Vec<i32>, postorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
    let n = inorder.len();
    let mut d: HashMap<i32, usize> = HashMap::new();
    for i in 0..n {
      d.insert(inorder[i], i);
    }
    fn dfs(
      postorder: &[i32],
      d: &HashMap<i32, usize>,
      i: usize,
      j: usize,
      n: usize
    ) -> Option<Rc<RefCell<TreeNode>>> {
      if n <= 0 {
        return None;
      }
      let val = postorder[j + n - 1];
      let k = *d.get(&val).unwrap();
      let left = dfs(postorder, d, i, j, k - i);
      let right = dfs(postorder, d, k + 1, j + k - i, n - 1 - (k - i));
      Some(Rc::new(RefCell::new(TreeNode { val, left, right })))
    }
    dfs(&postorder, &d, 0, 0, n)
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文