剑指 Offer 07. 重建二叉树

剑指 Offer 07. 重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

分析:

前序遍历的顺序为:根左右 中序遍历的顺序为:左根右

递归思想:

  1. 我们先根据前序遍历序列的第一个确定根,然后在中序遍历的序列中找到根的位置,根左边的就是其左子树,右边就是其右子树
  2. 构建根和左右子树
  3. 递归的进行1和2

方法1:

func reConstructBinaryTree(pre []int, in []int) *TreeNode {
    if len(pre) != len(in) || len(pre) == 0 { 
        return nil 
    }
    // find root and root Index in inOrder
    rootVal := pre[0]
    rootIndex := 0
    for i := 0; i < len(in); i++ {
        if in[i] == rootVal {
            rootIndex = i
        }
    }
    // pre and in for left and right 
    inL, inR := in[:rootIndex], in[rootIndex+1:]
    preL, preR := pre[1:rootIndex+1], pre[rootIndex+1:]
    // revursive
    left := reConstructBinaryTree(preL, inL)
    right := reConstructBinaryTree(preR, inR)
    return &TreeNode{Val: rootVal, Left: left, Right: right}
}

 

方法2:

class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if (!preorder.size()) {
            return nullptr;
        }
        TreeNode* root = new TreeNode(preorder[0]);
        stack<TreeNode*> stk;
        stk.push(root);
        int inorderIndex = 0;
        for (int i = 1; i < preorder.size(); ++i) {
            int preorderVal = preorder[i];
            TreeNode* node = stk.top();
            if (node->val != inorder[inorderIndex]) {
                node->left = new TreeNode(preorderVal);
                stk.push(node->left);
            }
            else {
                while (!stk.empty() && stk.top()->val == inorder[inorderIndex]) {
                    node = stk.top();
                    stk.pop();
                    ++inorderIndex;
                }
                node->right = new TreeNode(preorderVal);
                stk.push(node->right);
            }
        }
        return root;
    }
};

 

上一篇:hivalric Blossom


下一篇:Leetcode84, 739