C++ postorder traverse solution


  • 5
    S
    class Solution {
    public:
        int findTilt(TreeNode* root) {
            if(root == NULL) return 0;
            
            int res = 0;
            
            postorder(root, res);
            
            return res;
        }
    private:
        int postorder(TreeNode* root, int& res){
            if(root == NULL) return 0;
            
            int leftsum= postorder(root->left,res);
            
            int rightsum = postorder(root->right,res);
            
            res += abs(leftsum - rightsum);
            
            return leftsum + rightsum + root->val;
            
        }
    };
    

  • 1
    Z

    @Sublele
    Good code!
    One comment. The first line of function findTilt is not necessary, because it is checked in function postorder.


Log in to reply
 

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