欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Construct Binary Tree from Inorder and Postorder Traversal

程序员文章站 2022-04-27 11:35:32
...

Construct Binary Tree from Inorder and Postorder Traversal
解析:明显的递归类型题目,与前序遍历和中序遍历确定二叉树思路是一样的
后序遍历: 左 右
中序遍历: 左
Construct Binary Tree from Inorder and Postorder Traversal
1.根据后序遍历中的最后一个元素在中序遍历中确定根节点的位置,区分左右子树
2.建立当前节点的指针,并将该指针的左指针left指向左子树,右指针right指向右子树
利用i表示根节点的下标,ileft表示中序遍历的起点,iright表示中序遍历的终点,pleft表示后序遍历的起点,pright表示后序遍历的终点
左子树的区间:中序遍历[ileft,i-1],后序遍历[pleft, pleft+i-left-1] i-left表示左子树的节点个数
右子树的区间:中序遍历[i+1,iright],后序遍历[pleft+i-left, pright-1] i-left表示左子树的节点个数

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return DFS(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
    }
    
    TreeNode* DFS(vector<int>& inorder, int ileft, int iright, 
                  vector<int>& postorder, int pleft, int pright){
        if (ileft > iright || pleft > pright) return NULL;
        int i = 0;
        for (i = ileft; i <= iright; ++i){ //在中序遍历序列中查找根
            if (postorder[pright] == inorder[i])
                break;
        }
        TreeNode* cur = new TreeNode(postorder[pright]);
        cur->left = DFS(inorder, ileft, i-1, postorder, pleft, pleft+i-ileft-1);
        cur->right = DFS(inorder, i+1, iright, postorder, pleft+i-ileft, pright-1);
        return cur;
    }
};