二刷
77.15 %
With Helper Function
class Solution {
public TreeNode addOneRow(TreeNode root, int v, int d) {
if (d <= 0) throw new IllegalArgumentException();
return addHelper(root, v, d, true);
}
private TreeNode addHelper(TreeNode root, int v, int d, boolean isLeft) {
if (d == 1) {
TreeNode result = new TreeNode(v);
if (isLeft) result.left = root;
else result.right = root;
return result;
}
if (root == null) return root;
root.left = addHelper(root.left, v, d - 1, true);
root.right = addHelper(root.right, v, d - 1, false);
return root;
}
}
Without Helper Function
47.92 %
class Solution {
public TreeNode addOneRow(TreeNode root, int v, int d) {
if (d == 1) {
TreeNode result = new TreeNode(v);
result.left = root;
return result;
}
if (root == null) return root;
if (d == 2) {
TreeNode left = new TreeNode(v);
TreeNode right = new TreeNode(v);
left.left = root.left;
right.right = root.right;
root.left = left;
root.right = right;
return root;
}
root.left = addOneRow(root.left, v, d - 1);
root.right = addOneRow(root.right, v, d - 1);
return root;
}
}
一刷
78.29 %
class Solution {
// d-1 root
// d TreeNode(v) TreeNode(v)
// d+1 root.left null null root.right
public TreeNode addOneRow(TreeNode root, int v, int d) {
if (d == 1) {
TreeNode result = new TreeNode(v);
result.left = root;
return result;
}
// TODO
addOneRowHelper(root, v, d);
return root;
}
private void addOneRowHelper(TreeNode root, int v, int d) {
if (root == null) return;
if (d == 2) {
TreeNode left = root.left;
TreeNode right = root.right;
root.left = new TreeNode(v);
root.left.left = left;
root.right = new TreeNode(v);
root.right.right = right;
return;
}
addOneRowHelper(root.left, v, d - 1);
addOneRowHelper(root.right, v, d - 1);
}
}
No comments:
Post a Comment