• LeetCode(95) Unique Binary Search Trees II


    题目

    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.
    描述

    confused what “{1,#,2,3}” means? > read more on how binary tree is serialized on OJ.

    OJ’s Binary Tree Serialization:
    The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.

    Here’s an example:
    ex
    The above binary tree is serialized as “{1,2,3,#,#,4,#,#,5}”.

    分析

    给定整数n,求输入元素为[1n]时,所构成的全部二叉查找树;

    我们都知道二叉查找树的特点,左子树节点值小于根节点,右子树节点值大于根节点。

    对于输入[1n],每个值 i 都可以作为根节点,小于i 的元素构成左子树,大于i 的元素构成右子树。

    所以,此题的解决办法为二叉树常用递归。

    AC代码

    class Solution {
    public:
        vector<TreeNode*> generateTrees(int n) {
            if (n <= 0)
                return vector<TreeNode *>(1 , NULL);
    
            //对值为 [1 , n]的每个元素都可做二叉查找树的根节点
            return generateTrees(1, n);
        }
    
        //构造根节点[lhs , rhs]的所有二叉查找树
        vector<TreeNode *> generateTrees(int lhs, int rhs)
        {
            if (lhs > rhs)
            {
                return vector<TreeNode *>(1 , NULL);
            }
    
            //存储每个查找树的根节点
            vector<TreeNode *> ret;
            for (int r = lhs; r <= rhs; r++)
            {
                //[lhs~r-1]间节点作为左子树,[r+1~rhs]间节点作为右子树
                vector<TreeNode *> lefts = generateTrees(lhs, r - 1);
                vector<TreeNode *> rights = generateTrees(r + 1, rhs);
    
                //链接符合要求的左右子树
                int lsize = lefts.size();
                int rsize = rights.size();
                for (int i = 0; i < lsize; ++i)
                {
                    for (int j = 0; j < rsize; ++j)
                    {
                        //当前节点作为根节点
                        TreeNode *root = new TreeNode(r);
                        root->left = lefts[i];
                        root->right = rights[j];
                        ret.push_back(root);
                    }//for
                }//for          
            }//for
            return ret;
        }
    };

    GitHub测试程序源码

  • 相关阅读:
    day23,xml 和面向对象
    day22,ConfigParser,subprocess,xlrd三个模块
    re的总结
    day20,日志和正则表达式
    day19,序列化与反序列化总结,和其它的有些模块
    字符串的内建函数
    字符串和编码
    python解释器分类
    git &github 快速入门
    do export method of oracle all database tables with dmp files.
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214812.html
Copyright © 2020-2023  润新知