Construct a binary tree from preorder and middle order traversal sequence
Title description: Given a tree, the pre-order traversal
preorder
and the middle-order traversalinorder
. Please construct a binary tree and return its root node.Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution one: recursive method
To construct a binary tree by recursive method, the recursive process is as follows:
- If the pre-order traversal sequence or the middle-order traversal sequence is empty, return the empty tree directly;
- Because the first value of the preorder traversal sequence is the root node, the root node is obtained first;
- Then get the number of nodes leftCount and rightCount of the left and right subtrees of the root node according to the position of the root node in the in-order traversal;
- Then call this method recursively to get the left and right subtrees of the current root node;
- Finally, the root node is returned.
import com.kaesar.leetcode.TreeNode;
import java.util.Arrays;
public class LeetCode_105 {
public static TreeNode buildTree(int[] preorder, int[] inorder) {
// 当前序遍历序列或者中序遍历序列为空时,直接返回空树
if (preorder == null || preorder.length == 0) {
return null;
}
// 前序遍历序列的第一个值为根节点
TreeNode root = new TreeNode(preorder[0]);
// 左子树节点的数量
int leftCount;
// 中序遍历序列中,根节点左边的节点都是根节点左子树的节点
for (leftCount = 0; leftCount < inorder.length; leftCount++) {
if (inorder[leftCount] == preorder[0]) {
break;
}
}
// 根据左子树节点数和总的节点数计算右子树节点的数量
int rightCount = inorder.length - 1 - leftCount;
// 递归调用得到当前节点的左右子树
root.left = buildTree(Arrays.copyOfRange(preorder, 1, leftCount + 1), Arrays.copyOfRange(inorder, 0, leftCount));
root.right = buildTree(Arrays.copyOfRange(preorder, leftCount + 1, preorder.length), Arrays.copyOfRange(inorder, leftCount + 1, inorder.length));
return root;
}
public static void main(String[] args) {
int[] preorder = new int[]{3, 9, 20, 15, 7};
int[] inorder = new int[]{9, 3, 15, 20, 7};
buildTree(preorder, inorder).print();
}
}
[Daily Message] My life has gone from hardship to ease without a strong heart. No one can accomplish anyone with one hand, the true God is in my heart. Only by working hard can we see the light!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。