Unique Binary Search Trees II[leetcode]

发布时间:2016-12-11 2:55:43 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"Unique Binary Search Trees II[leetcode]",主要涉及到Unique Binary Search Trees II[leetcode]方面的内容,对于Unique Binary Search Trees II[leetcode]感兴趣的同学可以参考一下。

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./** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; left = null; right = null; } * } */ public class Solution { public ArrayList<TreeNode> generateTrees(int n) { // Start typing your Java solution below // DO NOT write main() function return dfs(1, n); } public ArrayList<TreeNode> dfs(int begin, int end) { ArrayList<TreeNode> ret = new ArrayList<TreeNode>(); if(begin > end) { ret.add(null); return ret; } for(int i = begin; i <= end; i++) { ArrayList<TreeNode> leftTrees = dfs(begin, i - 1); ArrayList<TreeNode> rightTrees = dfs(i + 1, end); for(int j = 0; j < leftTrees.size(); j++) for(int k = 0; k < rightTrees.size(); k++) { TreeNode node = new TreeNode(i); ret.add(node); node.left = leftTrees.get(j); node.right = rightTrees.get(k); } } return ret; } }

上一篇:调用ie内核标签-浏览器
下一篇:【PAT】1025. PAT Ranking (25)

相关文章

相关评论