[LeetCode] Binary Tree Tilt 二叉樹的坡度


 

Given a binary tree, return the tilt of the whole tree.

The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.

The tilt of the whole tree is defined as the sum of all nodes' tilt.

Example:

Input: 
         1
       /   \
      2     3
Output: 1
Explanation: 
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1

 

Note:

  1. The sum of node values in any subtree won't exceed the range of 32-bit integer.
  2. All the tilt values won't exceed the range of 32-bit integer.

 

這道題讓我們求二叉樹的坡度,某個結點的坡度的定義為該結點的左子樹之和與右子樹之和的差的絕對值,這道題讓我們求所有結點的坡度之和。我開始的想法就是老老實實的按定義去做,用先序遍歷,對於每個遍歷到的結點,先計算坡度,根據定義就是左子樹之和與右子樹之和的差的絕對值,然后返回的是當前結點的tilt加上對其左右子結點調用求坡度的遞歸函數即可。其中求子樹之和用另外一個函數來求,也是用先序遍歷來求結點之和,為了避免重復運算,這里用哈希表來保存已經算過的結點,參見代碼如下:

 

解法一:

class Solution {
public:
    unordered_map<TreeNode*, int> m;
    int findTilt(TreeNode* root) {
        if (!root) return 0;
        int tilt = abs(getSum(root->left, m) - getSum(root->right, m));
        return tilt + findTilt(root->left) + findTilt(root->right);
    }
    int getSum(TreeNode* node, unordered_map<TreeNode*, int>& m) {
        if (!node) return 0;
        if (m.count(node)) return m[node];
        return m[node] = getSum(node->left, m) + getSum(node->right, m) + node->val;
    }
};

 

但是在論壇中看了大神們的帖子后,發現這道題最好的解法應該是用后序遍歷來做,因為后序遍歷的順序是左-右-根,那么就會從葉結點開始處理,這樣我們就能很方便的計算結點的累加和,同時也可以很容易的根據子樹和來計算tilt,參見代碼如下:

 

解法二:

class Solution {
public:
    int findTilt(TreeNode* root) {
        int res = 0;
        postorder(root, res);
        return res;
    }
    int postorder(TreeNode* node, int& res) {
        if (!node) return 0;
        int leftSum = postorder(node->left, res);
        int rightSum = postorder(node->right, res);
        res += abs(leftSum - rightSum);
        return leftSum + rightSum + node->val;
    }
};

 

參考資料:

https://discuss.leetcode.com/topic/87191/java-o-n-postorder-traversal

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM