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
        }
    }
}
posted @ 2020-08-13 09:55  EvanMeetTheWorld  阅读(12)  评论(0)    收藏  举报