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

Construct Binary Tree from Preorder and Inorder Traversal

程序员文章站 2022-06-18 17:46:37
...

Construct Binary Tree from Preorder and Inorder Traversal
解析: 思路类似根据中序和后序确定二叉树

/**
 * 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>& preorder, vector<int>& inorder) {
        return DFS(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
    }
    TreeNode* DFS(vector<int>& preorder, int pleft, int pright, 
                  vector<int>& inorder, int ileft, int iright){
        if (pleft > pright || ileft > iright) return NULL;
        int i = 0;
        for (i = ileft; i <= iright; ++i){ //寻找二叉树的根节点,根据中序遍历划分左右子树
            if (preorder[pleft] == inorder[i])
                break;
        }
        TreeNode* cur = new TreeNode(preorder[pleft]);
        //前序遍历:左子树的节点 pleft+1, pleft+i-ileft
        //中序遍历:左子树的节点 ileft, i-1       
        cur->left = DFS(preorder, pleft+1, pleft+i-ileft, inorder, ileft, i-1);
        //前序遍历:右子树的节点 pleft+i-ileft+1, pright
        //中序遍历:右子树的节点 i+1, iright  
        cur->right = DFS(preorder, pleft+i-ileft+1, pright, inorder, i+1, iright);
        return cur;
    }
};

[1]https://www.cnblogs.com/grandyang/p/4296500.html?spm=a2c4e.10696291.0.0.6f5c19a4UVoRNo