You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
it's a little bit difficult to solve this problem using backtrack. And life would be easier if we use a recursive function which return a list of all possible TreeNodes at the different layer of a tree. We use left and right boundary to determine how we would connect nodes to the left and right of current node.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */classSolution {
publicList<TreeNode> generateTrees(intn) {
returngenerate(1, n);
}
privateList<TreeNode> generate(intleft, intright){
List<TreeNode> res = newArrayList<TreeNode>();
if(left > right){
// add null is essential,it works as a dummy node. // We need to use if when traverse the list res.add(null);
returnres;
}
for(inti = left; i <= right; i++){
List<TreeNode> leftList = generate(left, i - 1);
List<TreeNode> rightList = generate(i + 1, right);
for(TreeNodeleftNode : leftList){
for(TreeNoderightNode : rightList){
TreeNodecur = newTreeNode(i);
cur.left = leftNode;
cur.right = rightNode;
res.add(cur);
}
}
}
returnres;
}
}