您的位置:首页 > 其它

LeetCode - 105. Construct Binary Tree from Preorder and Inorder Traversal

2016-07-04 20:53 537 查看
首先,当我们遇到Binary Tree相关的问题的时候,要考虑使用递归是否可以解决问题,这是一个常用的思路。

接下来我们来看一下这道题目,给出了一个binary tree的preorder, inorder traversal,根据前序遍历和中序遍历的性质,我们知道preorder的第一个元素必然是树的root,接着我们在inorder这个数组中找到root的index,那么root左侧的都是左子树中的元素,右侧都是右子树中的元素。看下面的例子:

preorder: [1, 2, 4, 3, 5, 6]

inorder: [4, 2, 1, 5, 3, 6]

首先可以发现1是树的root,接着分析出4,2在左子树中,5,3,6在右子数中。这样就把大的问题又分成了两个小的问题,分别是:

preorder1: [2, 4, 3, 5, 6]; preorder2:[3, 5, 6]

inorder1: [4, 2]; inorder2: [5, 3, 6]

这样又可以继续进行递归调用。如果binary tree比较balanced的话,那么时间复杂度为O(nlogn),如果binary tree几乎是一条线的话,那么时间复杂度为O(n * n),代码如下:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTreePreIn(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder){
if(preStart > preorder.length - 1 || inStart > inEnd) return null;

TreeNode root = new TreeNode(preorder[preStart]);
int inIndex = 0; // index of root in inorder
for(int i = inStart; i <= inEnd; i++){
if(inorder[i] == root.val) inIndex = i;
}
root.left = buildTreePreIn(preStart + 1, inStart, inIndex - 1, preorder, inorder);
root.right = buildTreePreIn(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, preorder, inorder);

return root;
}

public TreeNode buildTree(int[] preorder, int[] inorder) {
return buildTreePreIn(0, 0, inorder.length - 1, preorder, inorder);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息