LeetCode: Construct Binary Tree from Preorder and Inorder Traversal 解题报告

本文介绍了一种通过先序和中序遍历序列构建二叉树的方法。首先,从先序遍历中找到根节点;然后,在中序遍历中定位根节点位置,确定左右子树的节点数;最后,递归地构建左右子树。文章提供了一个Java实现示例。

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.

SOLUTION 1:

1. Find the root node from the preorder.(it is the first node.)

2. Try to find the position of the root in the inorder. Then we can get the number of nodes in the left tree.

3. 递归调用,构造左子树和右子树。

例子:

Pre:       4 2 1 3 6 5 7

Inorder: 1 2 3 4 5 6 7 

 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 TreeNode buildTree(int[] preorder, int[] inorder) {
12         // bug 3: consider when length is 0.
13         if (preorder == null || inorder == null || preorder.length == 0 || preorder.length != inorder.length) {
14             return null;
15         }
16         
17         // bug 4: end index is length - 1.
18         return buildTree(preorder, inorder, 0, preorder.length - 1, 0, preorder.length - 1);
19     }
20     
21     public TreeNode buildTree(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) {
22         // base case;
23         if (preStart > preEnd) {
24             return null;
25         }
26         
27         int rootVal = preorder[preStart];
28         TreeNode root = new TreeNode(rootVal);
29         
30         int pos = findTarget(inorder, rootVal, inStart, inEnd);
31         
32         // bug 5: left number is pos - instart can't add 1
33         int leftNum = pos - inStart;
34         
35         root.left = buildTree(preorder, inorder, preStart + 1, preStart + leftNum, inStart, pos - 1);
36         root.right = buildTree(preorder, inorder, preStart + leftNum + 1, preEnd, pos + 1, inEnd);
37         
38         return root;
39     }
40     
41     // bug 1: return type required.
42     // bug 2: this is not a bst. can't use binary search.
43     public int findTarget(int[] A, int target, int start, int end) {
44         for (int i = start; i <= end; i++) {
45             if (target == A[i]) {
46                 return i;
47             }
48         }
49         
50         return -1;
51     }
52 }
View Code

 

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/BuildTree.java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值