'LC 114. Flatten Binary Tree to Linked List Question
For the LC question here, I am struggling to find where I am going wrong with the recursive approach. I am able to do this problem iteratively, but I am not sure where I am going wrong with the recursive approach. If I can get some guidance, I would appreciate it
Iterative Solution (passes):
class Solution {
public void flatten(TreeNode root) {
List<Integer> preorderList = new ArrayList<>();
preorder(root, preorderList);
TreeNode flat = root;
for (int i = 1; i < preorderList.size(); i++) {
flat.left = null;
flat.right = new TreeNode(preorderList.get(i));
flat = flat.right;
}
}
public void preorder(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
list.add(root.val);
preorder(root.left, list);
preorder(root.right, list);
}
}
Recursive Solution (fails):
class Solution {
public void flatten(TreeNode root) {
List<Integer> preorderList = new ArrayList<>();
preorder(root, preorderList);
int[] idx = new int[1];
flat = build(preorderList, idx);
}
public TreeNode build(List<Integer> list, int[] idx) {
if (idx[0] == list.size()) {
return null;
}
TreeNode root = new TreeNode(list.get(idx[0]));
idx[0] += 1;
root.right = build(list, idx);
root.left = null;
return root;
}
public void preorder(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
list.add(root.val);
preorder(root.left, list);
preorder(root.right, list);
}
}
Solution 1:[1]
Your last 2 print statements are missing a closing ')'
import random
name = input("Please enter your name")
print(name)
integ = int(input(name + "," + " please enter an integer: "))
print(integ)
integ2 = int(input(name + "," + " please enter another integer: "))
print(integ2)
divis = (integ % integ2)
print(divis)
if divis == 0:
print(str(integ) + " is divisible by " + (str(integ2)))
else:
print(str(integ) + " is NOT divisible by " + (str(integ2)))
Solution 2:[2]
You have forgotten to close the brackets. It should be like this:
import random
name = input("Please enter your name")
print(name)
integ = int(input(name + "," + " please enter an integer: "))
print(integ)
integ2 = int(input(name + "," + " please enter another integer: "))
print(integ2)
divis = (integ % integ2)
print(divis)
if divis == 0:
print(str(integ) + " is divisible by " + (str(integ2)))
else:
print(str(integ) + " is NOT divisible by " + (str(integ2)))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Meny Issakov |
| Solution 2 | MusicMan24 |
