【leetcode刷题笔记】Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.


 

类似http://www.cnblogs.com/sunshineatnoon/p/3854935.html

只是子树的前序和中序遍历序列分别更新为:

//左子树:
left_prestart = prestart+1
left_preend = prestart+index-instart
//右子树
right_prestart = prestart+index-instart+1
right_preend =  preend

代码如下:

复制代码
 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[] preoder,int[] inorder,int prestart,int preend,int instart,int inend){
22         if(instart > inend)
23             return null;
24         TreeNode root = new TreeNode(preoder[prestart]);
25         int index = InorderIndex(inorder, root.val);
26         root.left = buildTreeRec(preoder, inorder, prestart+1, prestart+index-instart, instart, index-1);
27         root.right = buildTreeRec(preoder, inorder, prestart+index-instart+1, preend, index+1, inend);
28         
29         return root;
30     }
31     public TreeNode buildTree(int[] preorder, int[] inorder) {
32         return buildTreeRec(preorder, inorder, 0, preorder.length-1, 0, inorder.length-1);
33     }
34 }
复制代码
posted @   SunshineAtNoon  阅读(273)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示