zoukankan      html  css  js  c++  java
  • [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 题目总结

  • 相关阅读:
    服务器切换
    闭包函数
    函数对象+嵌套
    lvs讲解
    了解python
    rang enumerate
    set-集合功能介绍
    元组-tuple功能介绍
    dict-字典功能介绍
    list-列表功能介绍
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12936155.html
Copyright © 2011-2022 走看看