LeetCode114 Flatten Binary Tree to LinkedList
flatten a binary tree into a linkedlist, using preorder tranverse and do it in-place.
since it’s using preorder tranverse order, so we need to do some modifications on preorder code
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); //first we push right
if (cur.left != null) stack.push(cur.left);
if (!stack.isEmpty()) { //cur.right is already pushed in stack, so we can assign here to things we want
cur.right = stack.peek();
}
cur.left = null; //we have to set all cur.left to null, so that all we remain is a linkedtree with only right most branch exist
}
}
}

浙公网安备 33010602011771号