前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >前序遍历和中序遍历树构造二叉树

前序遍历和中序遍历树构造二叉树

作者头像
一份执着✘
发布2018-06-04 16:14:00
1.7K0
发布2018-06-04 16:14:00
举报

题意

根据前序遍历和中序遍历树构造二叉树. 注意事项你可以假设树中不存在相同数值的节点

样例

给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回如下的树:

   2
 /  \
1    3

思路

根据前序遍历和中序遍历的规律可得:

  1. 前序遍历的第一个就是整个树的根节点
  2. 这个根节点在中序遍历的左侧是其左子树,右侧是右子树
  3. 将每一个节点都看作是一个单独的树,根据此 规律1规律2 依次递归获取其左右子树的前序与中序遍历,直到前序遍历或中序遍历的长度仅剩1,则说明该节点为叶子节点,从而构造整棵树。

代码实现

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
 
public class Solution {
    /**
     *@param preorder : A list of integers that preorder traversal of a tree
     *@param inorder : A list of integers that inorder traversal of a tree
     *@return : Root of a tree
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {

		if (preorder.length == 0 || inorder.length == 0) {
			return null;
		}

		int root = preorder[0]; // 根据前序遍历的规律取第一个最为根节点
		TreeNode treeRoot = new TreeNode(root);

		int flag = -1;			// flag用于存放根节点root在中序遍历中的位置
		for (int i = 0; i < inorder.length; i++) {
			if (inorder[i] == root) {
				flag = i;
			}
		}
		
		//前序或中序遍历等于1,则说明已经是叶子节点,直接return即可,避免多余运算
		if (preorder.length == 1 || inorder.length == 1) {
			return treeRoot;
		}
		
		int[] child_InorderLeft = new int[flag];    					  //左侧子节点的中序遍历
		int[] child_InorderRight = new int[(inorder.length - 1) - flag];  //右侧子节点的中序遍历
		int[] child_PreorderLeft = new int[flag];						  //左侧子节点的前序遍历
		int[] child_PreorderRight = new int[child_InorderRight.length];	  //右侧子节点的前序遍历
		
		
		//从现有的中序遍历中拿到 左右子节点的中序遍历
		for (int i = 0; i < inorder.length; i++) {
			if (i < flag) {
				child_InorderLeft[i] = inorder[i];
			}
			else if ((i > flag) ){
				child_InorderRight[i - flag - 1] = inorder[i];
			}
		}
		
		//从现有的前序遍历中拿到 左右子节点的前序遍历
		for (int i = 1; i < preorder.length ; i++) {  //这里i从1开始,是因为i的preorder[0]为根节点
			if(i <= flag)
				child_PreorderLeft[i-1] = preorder[i];   //preorderSeed[i-1] 是因为要新左子树要从0存放,不然preorderSeed[0]就是空的,而且长度会不够
			else { 
				child_PreorderRight[i - flag - 1] = preorder[i];
			}
		}
		
		//递归调用获取左右子树
		treeRoot.left = buildTree(child_PreorderLeft,child_InorderLeft);
		treeRoot.right = buildTree(child_PreorderRight,child_InorderRight);
		
		return treeRoot;
	}
}

原题地址

LintCode:前序遍历和中序遍历树构造二叉树

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-07-052,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题意
  • 样例
  • 思路
  • 代码实现
  • 原题地址
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档