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.
OJ ' s Binary Tree serialization:
The serialization of a binary tree follows a level order traversal, where ' # ' signifies a path terminator where no node ex Ists below.
Here's an example:
1 / 2 3 / 4 5
The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}". Test instructions: It is possible to find a two interpolation tree consisting of n number.
Idea: N number can be used as the node of the tree, so each layer is selected a node, and then combined left and right two sub-tree case.
/** * 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 list<treenode> Generate Trees (int n) {return Dfs (0, n-1); } Private list<treenode> dfs (int beg, int end) {list<treenode> ans = new arraylist<treenode> (); if (beg ; End) {ans.add (null); return ans;} for (int i = beg; I <= end; i++) {list<treenode> left = Dfs (Beg, i-1); list<treenode> right = DFS (i+1, end), for (int j = 0; J < Left.size (), j + +) for (int k = 0; k < right.size (); +) {TreeNode tmp = new TreeNode (i+1); Ans.add (tmp); tmp.left = Left.get (j); tmp.right = Right.get (k);}} return ans;}}
Leetcode Unique Binary Search Trees II