码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer-重建二叉树

时间:2020-06-04 19:47:21      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:coder   style   ini   new   问题   title   小问题   interview   nbsp   

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
 
 

 

概念:

前序遍历:父节点->左子树->右子树

中序遍历:左子树->父节点->右子树

分析:

前序遍历数组:[1,2,3,4,5,6,7]

中序遍历数组:[3,2,4,1,6,5,7]

前序遍历从父节点开始,所以1是根节点;而中序遍历的顺序是  左子树-> 1 ->右子树,所以在中序遍历数组中,1左边是左子树,1右边是右子树。

[3,2,4] 是左子树,[6,5,7]是右子树;

以左子树为例,再看前序遍历数字下一个节点是2,所以2是左子树的父节点,2左边是左子树,即[3],2右边是右子树,即[4]。

所以 大问题分解为小问题,最后一棵树为一个节点,直接创建。

 

注意点:

1、当只有左子树或者右子树时,左边界可能大于右边界。

 

 

 

 

 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     private int pos = 0;
12     public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
13         if(pre.length == 0){
14             return null;
15         }
16         return buildTree(pre,in,0,pre.length -1);
17     }
18     
19     public TreeNode buildTree(int [] pre,int [] in,int l,int r){
20         //只有左子树或只有右子树时,会产生左边界比右边界大的情况
21         if(l>r){
22             return null;
23         }
24         //只有一个节点时,创建并返回
25         if(l==r){
26             TreeNode node = new TreeNode(pre[pos]);
27             pos++;
28             return node;
29         }
30         //创建当前节点
31         TreeNode cur = new TreeNode(pre[pos]);
32         //在中序遍历数组中找到当前节点的位置
33         int i=l;
34         for(;i<=r;i++){
35             if(in[i]==pre[pos]){
36                 break;
37             }        
38         }
39         //找到相应节点后,前序遍历数组变量位置才加+
40         pos++;
41         //分别创建当前节点的左右子节点
42         cur.left = buildTree(pre,in,l,i-1);
43         cur.right = buildTree(pre,in,i+1,r);
44         return cur;
45     }
46 }

 

剑指offer-重建二叉树

标签:coder   style   ini   new   问题   title   小问题   interview   nbsp   

原文地址:https://www.cnblogs.com/MoonBeautiful/p/13045303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!