• 【leetcode】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.


    题解:如下图所示的一棵树:

            5
    
          /   
    
        2      4
    
      /         
    
    1      3       6

    中序遍历序列:1  2  3  5  4  6

    后序遍历序列:1  3  2  6  4  5

    后序遍历序列的最后一个元素就是当前根节点元素。首先想到的方法是递归,重要的是在先序和中序序列中分清楚哪一部分是左子树的,哪一部分是右子树的。

    递归的过程如下图所示:其中in和po分别代表递归调用时传递给左子树的中序遍历序列和后序遍历序列。

    以第一次递归为例,说明左右子树的中序和后序遍历序列如何求:

    如上图所示,现在中序序列中找到根节点的位置(5),就能够知道左子树(绿色圈)和右子树(橙色圈)的中序遍历序列了。然后根据中序遍历的长度等于后序遍历的长度,计算出左右子树的后序遍历序列,递归调用构造树函数即可。

    代码如下:

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public int InorderIndex(int[] inorder,int key){
    12         if(inorder == null || inorder.length == 0)
    13             return -1;
    14         
    15         for(int i = 0;i < inorder.length;i++)
    16             if(inorder[i] == key)
    17                 return i;
    18         
    19         return -1;
    20     }
    21     public TreeNode buildTreeRec(int[] inorder,int[] postorder,int instart,int inend,int postart,int poend){
    22         if(instart > inend)
    23             return null;
    24         TreeNode root = new TreeNode(postorder[poend]);
    25         int index = InorderIndex(inorder, root.val);
    26         root.left = buildTreeRec(inorder, postorder, instart, index-1, postart, postart+index-instart-1);
    27         root.right = buildTreeRec(inorder, postorder, index+1, inend, postart+index-instart, poend-1);
    28         
    29         return root;
    30     }
    31     public TreeNode buildTree(int[] inorder, int[] postorder) {
    32         return buildTreeRec(inorder, postorder, 0, inorder.length-1, 0, postorder.length-1);
    33     }
    34 }
  • 相关阅读:
    【入门】WebRTC知识点概览 | 内有技术干货免费下载
    mysql数据库运维方案
    前端报504错误如何定位
    Python数据分析之双色球高频数据统计
    利用Dapper ORM搭建三层架构
    ASP.NET和IIS工作原理
    C#中的new修饰符
    .NET 三层架构的简单规划
    Docker Hub中拉取镜像时出现超时问题该如何做?
    项目组件:分页(pagination)
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3854935.html
Copyright © 2020-2023  润新知