转自官方题解
如何遍历一棵树
有两种通用的遍历树的策略:
-
宽度优先搜索(
BFS
)我们按照高度顺序一层一层的访问整棵树,高层次的节点将会比低层次的节点先被访问到。
-
深度优先搜索(
DFS
)在这个策略中,我们采用
深度
作为优先级,以便从跟开始一直到达某个确定的叶子,然后再返回根到达另一个分支深度优先搜索策略又可以根据根节点、左孩子和右孩子的相对顺序被细分为前序遍历
,中序遍历
和后序遍历
。
下图中的顶点按照访问的顺序编号,按照 1-2-3-4-5
的顺序来比较不同的策略。
本问题就是从前序和中序遍历序列构造对应的二叉树。
方法 1:递归
结构定义
首先,定义树的存储结构 TreeNode
。
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
算法
如上文所提到的,先序遍历的顺序是 Root -> Left -> Right,这就能方便的从根开始构造一棵树。
首先,preorder 中的第一个元素一定是树的根,这个根又将 inorder 序列分成了左右两棵子树。现在我们只需要将先序遍历的数组中删除根元素,然后重复上面的过程处理左右两棵子树。
class Solution {
// start from first preorder element
int pre_idx = 0;
int[] preorder;
int[] inorder;
HashMap<Integer, Integer> idx_map = new HashMap<Integer, Integer>();
public TreeNode helper(int in_left, int in_right) {
// if there is no elements to construct subtrees
if (in_left == in_right)
return null;
// pick up pre_idx element as a root
int root_val = preorder[pre_idx];
TreeNode root = new TreeNode(root_val);
// root splits inorder list
// into left and right subtrees
int index = idx_map.get(root_val);
// recursion
pre_idx++;
// build left subtree
root.left = helper(in_left, index);
// build right subtree
root.right = helper(index + 1, in_right);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
this.preorder = preorder;
this.inorder = inorder;
// build a hashmap value -> its index
int idx = 0;
for (Integer val : inorder)
idx_map.put(val, idx++);
return helper(0, inorder.length);
}
}
复杂度分析
时间复杂度:O( n ),我们用主定理来计算时间复杂度:
这个方程表示在
的时间内将问题分成
个大小为
的子问题解决。
当前将问题分解成了两个子问题
a = 2
,每个子问题(计算左右两棵子树)的大小是原始问题的一般b = 2
,同时划分只需要常数的时间d = 0
。这意味着
,因此适用于主定理的第一种情况,时间复杂度为
。
空间复杂度:O( n ),存储整棵树的开销。