首页 > 代码库 > Unique Binary Search Trees II
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?
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:
1 / 2 3 / 4 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.答案
/** * 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 TreeNode copyNode(TreeNode node) { if(node==null) { return null; } TreeNode nodeCopy=new TreeNode(node.val); List<TreeNode> listOriginal=new LinkedList<TreeNode>(); List<TreeNode> listCopy=new LinkedList<TreeNode>(); listOriginal.add(node); listCopy.add(nodeCopy); while(listOriginal.size()>0) { TreeNode original=listOriginal.get(0); TreeNode copy=listCopy.get(0); if(original.left!=null) { copy.left=new TreeNode(original.left.val); listOriginal.add(original.left); listCopy.add(copy.left); } if(original.right!=null) { copy.right=new TreeNode(original.right.val); listOriginal.add(original.right); listCopy.add(copy.right); } listOriginal.remove(0); listCopy.remove(0); } return nodeCopy; } public List<TreeNode> generateTrees(int start,int end) { List<TreeNode> result=new LinkedList<TreeNode>(); TreeNode root=null; if(start>end) { result.add(null); return result; } for(int i=start;i<=end;i++) { List<TreeNode> listLeft=generateTrees(start,i-1); List<TreeNode> listRight=generateTrees(i+1,end); for(TreeNode left:listLeft) { for(TreeNode right:listRight) { root=new TreeNode(i); root.left=copyNode(left); root.right=copyNode(right); result.add(root); } } } return result; } public List<TreeNode> generateTrees(int n) { if(n<0) { return new LinkedList<TreeNode>(); } return generateTrees(1,n); } }
Unique Binary Search Trees II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。