zoukankan      html  css  js  c++  java
  • LeetCode:Unique Binary Search Trees

    问题描写叙述:

    Given n, how many structurally unique BST's (binary search trees) that store values 1...n?

    For example,
    Given n = 3, there are a total of 5 unique BST's.

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

    解题思路:分别考虑由1-n作为根节点。当以i作为跟节点时。其左子树节点数为i-1。右子树的节点数为n-i。以相同的方法递归地求左子树和右子树可能形成的二分查找树的个数为leftSubTree和rightSubTree。则以i做为根节点时所能形成的二分查找树的个数为leftSubTree*rightSubTree。将各节点的leftSubTree*rightSubTree求和既得所求。

    代码:

    public class Solution {
        public int numTrees(int n) {
           int sum = 0;
           int i;
           if(n == 0 || n == 1)
               return 1;
           for(i = 1;i <= n;i++)
           {
               int leftSubTree = numTrees(i - 1);
               int rightSubTree = numTrees(n - i);
               sum = sum + leftSubTree * rightSubTree;
           }
           return sum;
        }
    }








  • 相关阅读:
    http
    node 学习 http
    socket.io
    每日日报
    每日日报
    每日日报
    06人件读书笔记之一
    每日日报
    每日日报
    05程序员修炼之道:从小工到专家阅读笔记之三
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5081593.html
Copyright © 2011-2022 走看看