95. Unique Binary Search Trees II (Tree; DFS)

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,
Given n = 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

思路:结果要保留树的所有节点,所以每次都new出新节点。

new新节点的顺序是从下往上(否则在遍历到子节点的时候,还得深度拷贝所有的父辈节点),所以要先访问左、右儿子,再访问根节点=>后序遍历。

class Solution {
public:
    vector<TreeNode*> generateTrees(int n) {
        vector<TreeNode*> result;
        if(n==0)
        {
            return result;
        }
        postOrderTraverse(1,n, result);
        return result;
    }
    
    void postOrderTraverse(int start, int end, vector<TreeNode*> &rootArray)
    {
        if(start == end){ //递归结束条件:碰到叶子节点(没有子节点)
            rootArray.push_back(new TreeNode(start));
            return;
        }
        
        for(int i = start; i<=end; i++){ //iterate all roots
            vector<TreeNode*> leftTree;
            vector<TreeNode*> rightTree;
            if(i > start){ //build left tree
                postOrderTraverse(start, i-1, leftTree); 
            }
            if(i < end){ //build right tree
                postOrderTraverse(i+1, end, rightTree); 
            }
            
            //visit root: build a new tree for each (leftTree, rightTree) pair
            if(leftTree.empty()){
                for(int j = 0; j< rightTree.size(); j++){
                    TreeNode* root = new TreeNode(i); 
                    root->right = rightTree[j];
                    rootArray.push_back(root);
                 }
            }
            else if(rightTree.empty()){
                 for(int j = 0; j< leftTree.size(); j++){
                     TreeNode* root = new TreeNode(i); 
                     root->left = leftTree[j];
                     rootArray.push_back(root);
                 }
            }
            else{
                 for(int j = 0; j< leftTree.size(); j++)
                 {
                     for(int k = 0; k< rightTree.size(); k++)
                     {
                         TreeNode* root = new TreeNode(i);
                         root->left = leftTree[j];
                         root->right = rightTree[k];
                         rootArray.push_back(root);
                     }
                 }
            }
        }  
    }
};

 

posted on 2015-10-04 12:22  joannae  阅读(286)  评论(0编辑  收藏  举报

导航