Java 6 lines


  • 6

    Reversed inorder traversal.

    public class Solution {
        public TreeNode convertBST(TreeNode root) {
            if(root == null) return null;
            DFS(root, 0);
            return root;
        }
        
        public int DFS(TreeNode root, int preSum){
            if(root.right != null) preSum = DFS(root.right, preSum);
            root.val = root.val + preSum;
            return (root.left != null) ? DFS(root.left, root.val) : root.val;
        }
    }
    

  • 0
    W

    @fallcreek said in Java 6 lines:

    oot.val

    Elegant.


Log in to reply
 

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