已知二叉树的前序和中序遍历,构建该二叉树

28 篇文章 2 订阅

   先说说原理吧:

  1. 前序遍历的第一个节点必然是树的根节点
  2. 通过第1个节点将中序遍历分割为两部分,左边的就是树的左子树的节点,右边就是树的右子树的节点
  3. 重复1,2步,直至构建一颗完整的二叉树
  Java代码:
    
// 前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
		public TreeNode reConstructBinaryTree(int[] pre, int[] in)
			{
				if (pre == null || in == null || pre.length != in.length)
					return null;
				TreeNode pHeadNode = new TreeNode(pre[0]);
				int i = 0;
				for (i = 0; i < in.length; i++)
					if (pre[0] == in[i])
						break;
				pHeadNode.left = reConstructBinaryTree(pre, in, 1, 0, i - 1);
				pHeadNode.right = reConstructBinaryTree(pre, in, i + 1, i + 1,
						in.length - 1);
				return pHeadNode;
			}
		/**
		 * @param pre 前序遍历的数组
		 * @param in	中序遍历的数组
		 * @param mid  根节点的值
		 * @param start 子树的开始节点
		 * @param end 子树的开始节点
		 * @return
		 */
		public TreeNode reConstructBinaryTree(int[] pre, int[] in, int mid,
				int start, int end)
			{
				if (end < start)
					return null;
				TreeNode node = new TreeNode(pre[mid]);
				if (end == start)
					return node;
				int i = 0;
				for (i = start; i <= end; i++)
					if (pre[mid] == in[i])
						break;
				if (i == start)
					node.left = null;
				else
					node.left = reConstructBinaryTree(pre, in, mid + 1, start,
							i - 1);
				if (i == end)
					node.right = null;
				else
					node.right = reConstructBinaryTree(pre, in, mid + 1 + i
							- start, i + 1, end);
				return node;
			}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值