LeetCode 114. Flatten Binary Tree to Linked List?
Given a binary tree, flatten it to a linked list in-place.
although it looks kind of simple but don’t even know how to implement that.
it is preorder traverse with a little modification.
class Solution {
public void flatten(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<>();//仍然stack
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
if (cur.right != null) stack.push(cur.right);
if (cur.left != null) stack.push(cur.left);
if (!stack.isEmpty()) {
cur.right = stack.peek(); //peek the left most so far
}
cur.left = null;
}
}
}

浙公网安备 33010602011771号