106.ConstructBinaryTreefromInorderandPostorderTraversal

你快乐吗?

Posted by bbkgl on September 26, 2019

106. Construct Binary Tree from Inorder and Postorder Traversal


106. Construct Binary Tree from Inorder and Postorder Traversal

以下思路参考柳婼文章:已知后序与中序输出前序(先序)

C++。首先要知道一个结论,前序/后序+中序序列可以唯一确定一棵二叉树,所以自然而然可以用来建树。

看一下中序和后序有什么特点,中序[9,3,15,20,7] ,后序[9,15,7,20,3]

有如下特征:

  1. 后序中右起第一位3肯定是根结点,我们可以据此找到中序中根结点的位置rootin
  2. 中序中根结点左边就是左子树结点,右边就是右子树结点,即[左子树结点,根结点,右子树结点],我们就可以得出左子树结点个数为int left = rootin - leftin;
  3. 后序中结点分布应该是:[左子树结点,右子树结点,根结点]
  4. 根据前一步确定的左子树个数,可以确定后序中左子树结点和右子树结点的范围;
  5. 如果我们要前序遍历生成二叉树的话,下一层递归应该是:
    • 左子树:root->left = pre_order(中序左子树范围,后序左子树范围,中序序列,后序序列);
    • 右子树:root->right = pre_order(中序右子树范围,后序右子树范围,中序序列,后序序列);
  6. 每一层递归都要返回当前根结点root

代码如下:

class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return pre_order(0, inorder.size() - 1, 0, inorder.size() - 1, inorder, postorder);
    }
    
    TreeNode *pre_order(int leftin, int rightin, int leftpost, int rightpost, vector<int> &in, vector<int> &post) {
        if (leftin > rightin) return NULL;
        TreeNode *root = new TreeNode(post[rightpost]);
        int rootin = leftin;
        while (rootin <= rightin && in[rootin] != post[rightpost]) rootin++;
        int left = rootin - leftin;
        root->left = pre_order(leftin, rootin - 1, leftpost, leftpost + left - 1, in, post);
        root->right = pre_order(rootin + 1, rightin, leftpost + left, rightpost - 1, in, post);
        return root;
    }
};