Simple java solution


  • 2
    H
    public void flatten(TreeNode root) {
        // write your code here
        Stack<TreeNode> stack = new Stack<>();
        if (root == null) {return;}
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            TreeNode left = node.left;
            TreeNode right = node.right;
            node.left = null;
            if (right != null) {stack.push(right);}
            if (left != null) {stack.push(left);}
            if (left != null) {
                node.right = left;
            } else {
                node.right = stack.isEmpty()? right: stack.peek();
            }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.