1. 程式人生 > >[LeetCode][563] Binary Tree Tilt題解

[LeetCode][563] Binary Tree Tilt題解

[LeetCode][563] Binary Tree Tilt題解


給定一個樹,定義一個樹的左右子樹的差值的絕對值為樹的坡度。
要求返回樹的所有節點的坡度的和

dfs搜尋左右子樹的和 然後相減取絕對值,將這個結果累加到全域性變數res上
dfs作用即是記錄當前樹的總和,以便它的父親呼叫(回溯時候呼叫)


/*
 * [563] Binary Tree Tilt
 *
 * https://leetcode.com/problems/binary-tree-tilt/description/
 *
 * algorithms
 * Easy (46.46%)
 * Total Accepted:    39.4K
 * Total Submissions: 84.9K
 * Testcase Example:  '[1,2,3]'
 *
 * 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:
 *
 * The sum of node values in any subtree won't exceed the range of 32-bit
 * integer.
 * All the tilt values won't exceed the range of 32-bit integer.
 *
 *
 */
/** * 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 { private: int res; public: int findTilt(TreeNode *root) { res = 0
; dfs(root); return res; } //返回的當前節點的左右子樹和自己節點的和 //因此 //每一次dfs 用temp記錄當前的累加值 //而使用dfs的返回值(當前樹的總共的值)作為返回給父親節點來呼叫 int dfs(TreeNode *root) { if (root == nullptr) { return 0; } //如果是葉子節點 int l=dfs(root->left); int
r=dfs(root->right); res+=abs(l-r); return l+r+root->val; } };

參考https://leetcode.com/problems/binary-tree-tilt/discuss/102323/C+±easy-and-clean-soluion