114. Flatten Binary Tree to Linked List

Link

Solution

rightNode會變leftNode, 而leftNode會在處理完所有右子樹後才開始處理

class Solution {
    public void flatten(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        TreeNode preNode = null;
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            if(node.right != null) stack.push(node.right);
            if(node.left != null) stack.push(node.left);
            if(preNode != null){
                preNode.right = node;
                preNode.left = null;
            }
            preNode = node;
        }       
    }
}

Last updated

Was this helpful?