【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 }
复制代码
posted @   SunshineAtNoon  阅读(249)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示