1. 程式人生 > >不同的二叉查詢樹 II -LintCode

不同的二叉查詢樹 II -LintCode

給出n,生成所有由1…n為節點組成的不同的二叉查詢樹
樣例
給出n = 3,生成所有5種不同形態的二叉查詢樹:
這裡寫圖片描述

#ifndef C164_H
#define C164_H
#include<iostream>
#include<vector>
using namespace std;
class TreeNode{
public:
    int val;
    TreeNode *left, *right;
    TreeNode(int val)
    {
        this->val = val;
        this->left = this
->right = NULL; } }; class Solution { public: /** * @paramn n: An integer * @return: A list of root */ vector<TreeNode *> generateTrees(int n) { // write your code here vector<TreeNode *> vTree; if (n < 0) return vTree; vTree = build(1
, n); return vTree; } //構建start到end所有不同的二叉樹 vector<TreeNode*> build(int start, int end) { vector<TreeNode*> vTree; if (start > end) { vTree.push_back(NULL); return vTree; } //對於i,左子樹為start到i-1,右子樹為i+1到end
//並且遍歷左右子樹的每一種情況 for (int i = start; i <= end; ++i) { vector<TreeNode*> left = build(start, i - 1); vector<TreeNode*> right = build(i + 1, end); for (int j = 0; j < left.size(); ++j) { for (int k = 0; k < right.size(); ++k) { TreeNode* node = new TreeNode(i); node->left = left[j]; node->right = right[k]; vTree.push_back(node); } } } return vTree; } }; #endif