zoukankan      html  css  js  c++  java
  • leetcode--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.

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

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

     

    This method to this problem is similar to Unique Binary Search Trees.

     

    public class Solution {
        public ArrayList<TreeNode> generateTrees(int n) {
             return treeHelp(1, n);
        }
    	public ArrayList<TreeNode> treeHelp(int l, int n){
    		ArrayList<TreeNode> result = new ArrayList<TreeNode>();
    		if(l > n){ // no TreeNode can be generated 
    			result.add(null);
    			return result;
    		}
    		else{
    			for(int i = l; i <= n; ++i){
    				ArrayList<TreeNode> leftNode = treeHelp(l, i - 1);
    				ArrayList<TreeNode> rightNode = treeHelp(i + 1, n);
    				for(int j = 0; j < leftNode.size(); ++j){
    					for(int m = 0; m < rightNode.size(); ++m){
    						TreeNode root = new TreeNode(i);
    						root.left = leftNode.get(j);
    						root.right = rightNode.get(m);
    						result.add(root);
    					}
    				}
    			}		
    		}
    		return result;
        }
    }
    

      

  • 相关阅读:
    前端基础之BOM和DOM
    前端基础之JavaScript
    前端基础之CSS
    Black And White HDU
    Robot Motion HDU
    A Knight's Journey POJ
    Find a way HDU
    排序 HDU
    Dungeon Master POJ
    Network Saboteur POJ
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3537453.html
Copyright © 2011-2022 走看看