leetcode 563
Posted 热之雪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 563相关的知识,希望对你有一定的参考价值。
563. Binary Tree Tilt
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
/** * 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 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; } };
566. Reshape the Matrix
class Solution { public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { int m = nums.size(), n = nums[0].size(), o = m * n; if (r * c != o) return nums; vector<vector<int>> res(r, vector<int>(c, 0)); for (int i = 0; i < o; i++) res[i / c][i % c] = nums[i / n][i % n]; return res; } };
572. Subtree of Another Tree
/** * 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 { vector<TreeNode*> nodes; public: bool isSubtree(TreeNode* s, TreeNode* t) { if (!s && !t) return true; if (!s || !t) return false; getDepth(s, getDepth(t, -1)); for (TreeNode* n: nodes) if (identical(n, t)) return true; return false; } int getDepth(TreeNode* r, int d) { if (!r) return -1; int depth = max(getDepth(r->left, d), getDepth(r->right, d)) + 1; // Check if depth equals required value // Require depth is -1 for tree t (only return the depth, no push) if (depth == d) //递归回去得时候,从树下开始记达到深度位d时记下 nodes.push_back(r); return depth; } bool identical(TreeNode* a, TreeNode* b) { if (!a && !b) return true; if (!a || !b || a->val != b->val) return false; return identical(a->left, b->left) && identical(a->right, b->right); } };
581. Shortest Unsorted Continuous Subarray
Input: [2, 6, 4, 8, 10, 9, 15] Output: 5 Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
class Solution { public int findUnsortedSubarray(int[] A) { int n = A.length, beg = -1, end = -2, min = A[n-1], max = A[0]; for (int i=1;i<n;i++) { max = Math.max(max, A[i]); min = Math.min(min, A[n-1-i]); if (A[i] < max) end = i; if (A[n-1-i] > min) beg = n-1-i; } return end - beg + 1; } }
以上是关于leetcode 563的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode-563-Binary Tree Tilt]
LeetCode 563. Binary Tree Tilt
LeetCode - 563. Binary Tree Tilt