总结重建二叉树的递归和迭代做法
来源
剑指Offer 面试题7:重建二叉树
LC105:根据前中序遍历重建二叉树
LC106:根据后中序遍历重建二叉树
思路
不论使用递归还是迭代,基本的思路都是一致的:从前/后序数组中确定根,再根据中序遍历数组来划分左右子树。
递归
思路:分而治之,每次递归实现的功能都是一致的,根据前/后序遍历数组确定根,再根据根在中序遍历数组中的位置来划分左右子树的范围。
方法一
需要维护一个哈希表,用于记录中序遍历数组每个元素对应的下标,方便查找
以前中序重建为例:
class Solution {
HashMap<Integer, Integer> memo;
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length < 1 || preorder.length != inorder.length)
return null;
memo = new HashMap<>();
for (int i = 0; i < inorder.length; i++)
{
memo.put(inorder[i], i);
}
return bulidTreeRecursive(preorder, 0, 0, inorder.length - 1);
}
private TreeNode bulidTreeRecursive(int[] preorder, int rootIndex, int start, int end)
{
if (start > end)
return null;
TreeNode root = new TreeNode(preorder[rootIndex]);
int i = memo.get(preorder[rootIndex]);
root.left = bulidTreeRecursive(preorder, rootIndex + 1, start, i - 1);
root.right = bulidTreeRecursive(preorder, i - start + rootIndex + 1, 1 + i, end);
return root;
}
}
方法二
个人认为方法二优于方法一的地方在于,方法二只需要维护两个指针,相比于方法一的哈希表,在空间上更有优势。递归时传入一个参数stop,以前中序重建为例,stop的值为根节点的值,当中序遍历数组的指针指向根节点值的时候,说明左子树已经重建完毕;对右子树来说,当前序遍历数组的指针超出数组界限时,说明所有右子树都已经重建完毕。
以根据后中序遍历数组重建二叉树为例:
class Solution {
int postIndex;
int inIndex;
public TreeNode buildTree(int[] inorder, int[] postorder) {
int length = inorder.length;
if (length < 1 || length != postorder.length)
return null;
postIndex = length - 1; inIndex = length - 1;
return buildTreeRecursive(inorder, postorder, Integer.MAX_VALUE);
}
private TreeNode buildTreeRecursive(int[] inorder, int[] postorder, int stop)
{
if (postIndex < 0)
return null;
if (inorder[inIndex] == stop)
{
inIndex--;
return null;
}
TreeNode root = new TreeNode(postorder[postIndex--]);
root.right = buildTreeRecursive(inorder, postorder, root.val);
root.left = buildTreeRecursive(inorder, postorder, stop);
return root;
}
}
迭代法
实际上迭代法就是用栈模拟递归中第二种方法
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
int length = inorder.length;
if (length < 1 || length != postorder.length)
return null;
TreeNode root = new TreeNode(postorder[length - 1]);
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
int inIndex = length - 1;
for (int i = length - 2; i >= 0; i--)
{
TreeNode currNode = stack.peek();
if (currNode.val != inorder[inIndex])
{
currNode.right = new TreeNode(postorder[i]);
stack.push(currNode.right);
}
else
{
while (!stack.isEmpty() && stack.peek().val == inorder[inIndex])
{
currNode = stack.pop();
inIndex--;
}
currNode.left = new TreeNode(postorder[i]);
stack.push(currNode.left);
}
}
return root;
}
}