I am trying to solve this problem on leetcode: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ (Flatten binary tree into linkedlist)
This is my code:
class Solution{
TreeNode result;
public void flatten(TreeNode root) {
TreeNode res = flattenTree(root, null);
root = res;
}
private TreeNode flattenTree(TreeNode node, TreeNode temp) {
if (node == null) {
return node;
}
if (result == null) {
result = new TreeNode(node.val);
temp = result;
} else {
TreeNode result1 = new TreeNode(node.val);
result.right = result1;
result = result.right;
result.left = null;
}
flattenTree2(node.left, temp);
flattenTree2(node.right, temp);
return temp;
}
}
I believe this is the correct solution because after pointing to res, root contains the tree in correct format for example input data shown in the first screenshot. This, is the screenshot of inspecting the tree after the method executes.
But, still I am getting incorrect answer. The leetcode compiler says that the root has not changed at all. This is the outcome.
Not, sure what I need to do to make leetcode accept is as the correct solution.


