563. Binary Tree Tilt

來源:互聯網
上載者:User

標籤:leetcode   roo   思路   code   efi   .com   好的   int   div   

https://leetcode.com/problems/binary-tree-tilt/description/

挺好的一個題目,審題不清的話很容易做錯。主要是tilt of whole tree 的定義是sum of all node‘s tilt 而不是想當然的tilt of root.

一開是我就以為是簡單的tilt of root 導致完全錯誤。思路其實可以看作是求sum of children 的變種,只是這裡不僅要跟蹤每個子樹的sum 還要累計上他們的tilt。

 

/** * 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 tiltIter(TreeNode* root, int *t) {        if (root == nullptr) {            return 0;        }                int leftSum = 0;        int rightSum = 0;        if (root->left != nullptr) {            leftSum = tiltIter(root->left, t);        }        if (root->right != nullptr) {            rightSum = tiltIter(root->right, t);        }        //tilt of the current node;        int tilt = abs(leftSum - rightSum);        *t += tilt;        return root->val + leftSum + rightSum;    }        int findTilt(TreeNode* root) {        int tilt = 0;        tiltIter(root, &tilt);        return tilt;    }};

 

563. Binary Tree Tilt

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.