C++ DFS Solution


  • 0
    Y
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int findTilt(TreeNode* root) {
            int sum = 0;
            if(root == NULL)
                return sum;
            dfs(root, sum);
            return sum;
        }
    private:
        int dfs(TreeNode* root, int &sum){
            int lsum = 0, rsum = 0;
            if(root->left)
                lsum = dfs(root->left, sum);
            if(root->right)
                rsum = dfs(root->right, sum);
            sum += abs(lsum - rsum);
            return lsum + rsum + root->val;
        }
    };
    

Log in to reply
 

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