• LeetCode: Unique Binary Search Trees II


    贴下自己写的不用指针的代码,更加容易懂吧

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<TreeNode *> dfs(int start, int end) {
    13         vector<TreeNode *> subtree;
    14         if (start > end) {
    15             subtree.push_back(NULL);
    16             return subtree;
    17         }
    18         for (int i = start; i <= end; i++) {
    19             vector<TreeNode *> left = dfs(start, i-1);
    20             vector<TreeNode *> right = dfs(i+1, end);
    21             for (int j = 0; j < left.size(); j++) {
    22                 for (int k = 0; k < right.size(); k++) {
    23                     TreeNode *tmp = new TreeNode(i);
    24                     tmp->left = left[j];
    25                     tmp->right = right[k];
    26                     subtree.push_back(tmp);
    27                 }
    28             }
    29         }
    30         return subtree;
    31     }
    32     vector<TreeNode *> generateTrees(int n) {
    33         // Start typing your C/C++ solution below
    34         // DO NOT write int main() function
    35         return dfs(1, n);
    36     }
    37 };

     C#

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     public int val;
     5  *     public TreeNode left;
     6  *     public TreeNode right;
     7  *     public TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public List<TreeNode> GenerateTrees(int n) {
    12         return dfs(1, n);
    13     }
    14     public List<TreeNode> dfs(int start, int end) {
    15         List<TreeNode> subTree = new List<TreeNode>();
    16         if (start > end) {
    17             subTree.Add(null);
    18             return subTree;
    19         }
    20         for (int i = start; i <= end; i++) {
    21             List<TreeNode> left = dfs(start, i - 1);
    22             List<TreeNode> right = dfs(i + 1, end);
    23             for (int j = 0; j < left.Count; j++) {
    24                 for (int k = 0; k < right.Count; k++) {
    25                     TreeNode tmp = new TreeNode(i);
    26                     tmp.left = left[j];
    27                     tmp.right = right[k];
    28                     subTree.Add(tmp);
    29                 }
    30             }
    31         }
    32         return subTree;
    33     }
    34 }
    View Code
  • 相关阅读:
    selenium爬取沃尔玛分类和商品详情
    linux下部署redis
    linux系统基本操作命令
    Scrapy & Django项目
    爬虫爬取百度搜狗图片持久化存储
    django + vue 简单配置登录注册及分页和实例化
    vue安装及常用属性
    vue跨域配制
    Django中配置全文检索
    Django框架知识点简单总结(1)
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3035128.html
Copyright © 2020-2023  润新知