JAVA DFS beats 80%

  • 0

    Search the tree in descending order and pass the sum num to node it will add to.

    class Solution {
        public TreeNode convertBST(TreeNode root) {
            if(root == null) return root;
            dfs(root, 0);
            return root;
        public int dfs(TreeNode root, int sum){
            if(root.right != null){
                sum = dfs(root.right, sum);
            root.val += sum;
            if(root.left != null){
                return dfs(root.left, root.val);
            }else return root.val;

Log in to reply

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