[563. Binary Tree Tilt] C++_DFS method


  • 0
    class Solution {
    public:
    int res = 0;
    int findTilt(TreeNode* root) {
        if(root == nullptr) return res;
        dfs(root);
        return res;
    }
    
    int dfs(TreeNode* root){
        if(!root->left && !root->right) return root->val;
        int a = 0, b = 0;
        if(root->left){
            a = dfs(root->left);
        }
        if(root->right){
            b = dfs(root->right);
        }
        res += abs(a - b);//our final result.
        return a + b + root->val;//node value information, which will be used for calculating Tilt of its parent node.
    }
    };

Log in to reply
 

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