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;
        }
    }
}
posted @ 2020-11-19 02:51  EvanMeetTheWorld  阅读(15)  评论(0)    收藏  举报