【LeetCode】106. Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

这道题让我们用中序和后序遍历恢复出二叉树。这道题跟上一题解法一样,参考上一题:【LeetCode】105. Construct Binary Tree from Preorder and Inorder Traversal

首先还是需要明白中序和后序遍历的顺序:

1. 中序(先左再根后右);

2. 后序(先左再右后根)。

中序的二叉树组成:{左子树}根{右子树}

后序的二叉树组成:{左子树}{右子树}根

所以先从后序的最后一个元素找到根节点,然后根据找到的根节点将中序的左右子树划分出来。重复上述步骤。

/**
 * 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) {
        TreeNode* root=NULL;
        vector<int> in_l,in_r,ls_l,ls_r;
        int index = 0;
        
        if(!inorder.empty() && !postorder.empty()){
            root=new TreeNode(postorder.back());
            
            for(int i=0;i<inorder.size();i++){//找到根节点
                if(inorder[i]==postorder.back())
                    index=i;
            }
            for(int i=0;i<index;i++){//找到左子树
                in_l.push_back(inorder[i]);
                ls_l.push_back(postorder[i]);
            }
            for(int i=index+1;i<inorder.size();i++){//找到右子树
                in_r.push_back(inorder[i]);
                ls_r.push_back(postorder[i-1]);
            }
            root->left=buildTree(in_l,ls_l);
            root->right=buildTree(in_r,ls_r);
        }
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/poulang5786/article/details/82454094