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 ; int res = ; postorder(root, res); return res;
}
private:
int postorder(TreeNode* root, int& res){
if(root == NULL) return ; 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[].size(), o = m * n;
if (r * c != o) return nums;
vector<vector<int>> res(r, vector<int>(c, ));
for (int i = ; 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, -)); for (TreeNode* n: nodes)
if (identical(n, t))
return true; return false;
} int getDepth(TreeNode* r, int d) {
if (!r)
return -; int depth = max(getDepth(r->left, d), getDepth(r->right, d)) + ; // 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;
}
}

594. Longest Harmonious Subsequence

Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
int findLHS(vector<int>& nums) {
unordered_map<int,int>m;
for(auto i: nums)
m[i]++;
int res = 0;
for(auto it:m)
if(m.count(it.first-1)>0)
res = max(res, it.second+m[it.first-1]);
return res;
} ///////////////////////
int findLHS(vector<int>& nums) {
unordered_map<int,int>m;
int res = 0;
for(auto i: nums){
m[i]++;
if(m.count(i+1))
res = max(res, m[i] + m[i+1]);
if(m.count(i-1))
res = max(res, m[i] + m[i-1]);
}
return res;
} ///////////////////////////////////////
int findLHS(vector<int>& nums) {
sort(nums.begin(),nums.end());
int len = 0;
for(int i = 1, start = 0, new_start = 0; i<nums.size(); i++)
{ if (nums[i] - nums[start] > 1)
start = new_start;
if (nums[i] != nums[i-1])
new_start = i;
if(nums[i] - nums[start] == 1)
len = max(len, i-start+1);
}
return len;

599. Minimum Index Sum of Two Lists

Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["KFC", "Shogun", "Burger King"]
Output: ["Shogun"]
Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).
  vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
vector<string>res;
unordered_map<string,int>m;
int min = INT_MAX;
for(int i = ; i < list1.size(); i++) m[list1[i]] = i;
for(int i = ; i < list2.size(); i++)
if(m.count(list2[i]) != )
if(m[list2[i]] + i < min) min = m[list2[i]] + i, res.clear(), res.push_back(list2[i]);
else if(m[list2[i]] + i == min) res.push_back(list2[i]);
return res;
}

606. Construct String from Binary Tree

Input: Binary tree: [1,2,3,4]
1
/ \
2 3
/
4 Output: "1(2(4))(3)"

Explanation: Originallay it needs to be "1(2(4)())(3()())",
but you need to omit all the unnecessary empty parenthesis pairs.
And it will be "1(2(4))(3)".
class Solution {
public:
string tree2str(TreeNode* t) {
return !t ? "" : to_string(t->val) + (t->left ? "(" + tree2str(t->left) + ")" : t->right ? "()" : "")
+ (t->right ? "(" + tree2str(t->right) + ")" : "");
}
};

617. Merge Two Binary Trees

Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if (!t1 || !t2) return t1 ? t1 : t2; TreeNode* node = new TreeNode(t1->val + t2->val);
node->left = mergeTrees(t1->left, t2->left);
node->right = mergeTrees(t1->right, t2->right);
return node;
}
};

633. Sum of Square Numbers

Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
bool judgeSquareSum(int c) {
for(int i=;i<=sqrt(c);i++) {
int t=sqrt(c-i*i);
if(t*t==c-i*i) return true;
}
return false;
}

637. Average of Levels in Binary 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 {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
long temp=;
int s=q.size();
for(int i=;i<s;i++) {
TreeNode* t=q.front();
q.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
temp+=t->val;
}
res.push_back((double)temp/s);
}
return res;
}
};

645. Set Mismatch

Input: nums = [1,2,2,4]
Output: [2,3]

思路:使数组按123。。。n来排序,如果当前的内容和index不匹配,则交换

vector<int> findErrorNums(vector<int>& nums) {
for(int i = ; i<nums.size(); i++){
while(nums[i] != nums[nums[i] - ])swap(nums[i], nums[nums[i] - ]);
}
for(int i = ; i<nums.size() ; i++){
if(nums[i] != i + )return {nums[i], i + };
}
}

653. Two Sum IV - Input is a BST

Input:
5
/ \
3 6
/ \ \
2 4 7 Target = 9 Output: True
//方法一:使用map来进行一次遍历
bool findTarget(TreeNode* root, int k) {
unordered_set<int> set;
return dfs(root, set, k);
} bool dfs(TreeNode* root, unordered_set<int>& set, int k){
if(root == NULL)return false;
if(set.count(k - root->val))return true;
set.insert(root->val);
return dfs(root->left, set, k) || dfs(root->right, set, k);
} /////////////////////////////////////////////////////
//方法二:先使用中序遍历使其按小到大来排序,然后对排序后的数组进行首尾相加
bool findTarget(TreeNode* root, int k) {
vector<int> nums;
inorder(root, nums);
for(int i = , j = nums.size()-; i<j;){
if(nums[i] + nums[j] == k)return true;
(nums[i] + nums[j] < k)? i++ : j--;
}
return false;
} void inorder(TreeNode* root, vector<int>& nums){
if(root == NULL)return;
inorder(root->left, nums);
nums.push_back(root->val);
inorder(root->right, nums);
} /////////////////////////////////////////////////////// bool findTarget(TreeNode* root, int k) {
return dfs(root, root, k);
} bool dfs(TreeNode* root, TreeNode* cur, int k){
if(cur == NULL)return false;
return search(root, cur, k - cur->val) || dfs(root, cur->left, k) || dfs(root, cur->right, k);
} bool search(TreeNode* root, TreeNode *cur, int value){
if(root == NULL)return false;
return (root->val == value) && (root != cur)
|| (root->val < value) && search(root->right, cur, value)
|| (root->val > value) && search(root->left, cur, value);
}

leetcode 563 - 653的更多相关文章

  1. LeetCode 563. 二叉树的坡度(Binary Tree Tilt) 38

    563. 二叉树的坡度 563. Binary Tree Tilt 题目描述 给定一个二叉树,计算整个树的坡度. 一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值.空结点 ...

  2. LeetCode 563. Binary Tree Tilt (二叉树的倾斜度)

    Given a binary tree, return the tilt of the whole tree. The tilt of a tree node is defined as the ab ...

  3. Java实现 LeetCode 563 二叉树的坡度(又是一个遍历树)

    563. 二叉树的坡度 给定一个二叉树,计算整个树的坡度. 一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值.空结点的的坡度是0. 整个树的坡度就是其所有节点的坡度之和. ...

  4. 【LeetCode】653. Two Sum IV - Input is a BST 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:BFS 方法二:DFS 日期 题目地址:ht ...

  5. 【leetcode】653. Two Sum IV - Input is a BST

    Given the root of a Binary Search Tree and a target number k, return true if there exist two element ...

  6. LeetCode 653. 两数之和 IV - 输入 BST(Two Sum IV - Input is a BST)

    653. 两数之和 IV - 输入 BST 653. Two Sum IV - Input is a BST 题目描述 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定 ...

  7. leetcode 1.Two Sum 、167. Two Sum II - Input array is sorted 、15. 3Sum 、16. 3Sum Closest 、 18. 4Sum 、653. Two Sum IV - Input is a BST

    1.two sum 用hash来存储数值和对应的位置索引,通过target-当前值来获得需要的值,然后再hash中寻找 错误代码1: Input:[3,2,4]6Output:[0,0]Expecte ...

  8. Leetcode 653. 两数之和 IV - 输入 BST

    题目链接 https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/ 题目描述 给定一个二叉搜索树和一个目标结果,如果 B ...

  9. Leetcode题解 - 树、DFS部分简单题目代码+思路(700、671、653、965、547、473、46)

    700. 二叉搜索树中的搜索 - 树 给定二叉搜索树(BST)的根节点和一个值. 你需要在BST中找到节点值等于给定值的节点. 返回以该节点为根的子树. 如果节点不存在,则返回 NULL. 思路: 二 ...

随机推荐

  1. 现代软件工程HW1:词频统计

    作业详细要求:http://www.cnblogs.com/denghp83/p/8627840.html 基本功能 1. 统计文件的字符数(只需要统计Ascii码,汉字不用考虑,换行符不用考虑,'\ ...

  2. java中的Math类

    一般地,当需要使用数字的时候,我们通常使用内置数据类型,如:byte.int.long.double 等 在实际开发过程中,我们经常会遇到需要使用对象,而不是内置数据类型的情形.为了解决这个问题,Ja ...

  3. mac brew nginx php php-fpm xdebug

    /usr/local/opt/nginx/bin/nginx -v brew services restart nginx sudo /usr/local/sbin/php-fpm --fpm-con ...

  4. C++ AOP手法

    1.代理模式 2.模版 3.NVI(non-virtual interface) 参考:https://www.cnblogs.com/qicosmos/p/4772389.html <effe ...

  5. 容斥原理——hdu1796

    /* 遇到这种题一般用dfs,枚举起点来做 但是本题如何进行容斥? 比如以x为起点,第一步dfs到y,那么因子有lcm(x,y)的 所有数要被减掉(容斥中偶数是减法) 然后第二步dfs到z,那么因子有 ...

  6. 线性dp——求01串最大连续个数不超过k的方案数,cf1027E 好题!

    只写了和dp有关的..博客 https://www.cnblogs.com/huyufeifei/p/10351068.html 关于状态的继承和转移 这题的状态转移要分开两步来做: 1.继承之前状态 ...

  7. Js中的onblur和onfocus事件应用介绍

    html页面中,诸如按钮.文本框等可视元素都具有拥有和失去焦点的事件,本文以文本框获得和失去焦点为例简单讲解onfocus和onblur的应用 html页面中,诸如按钮.文本框等可视元素都具有拥有和失 ...

  8. 深入理解JVM(一)类加载器部分:双亲委派模型

    类加载器的父亲委托机制 在父亲委托机制中,各个类加载器按照父子关系形成了树形结构,除了根类加载器之外,其余的类加载器都有且只有一个父加载器. 先让最顶层可以加在的父加载器加栽(所有可加载的加载器中,处 ...

  9. myeclipse 无法部署项目到jboss服务器 部署不上去

    关于myeclipse部署项目到jboss点击add deployments没有反应的问题,如图 此处点击右键,选择add deployments没有反应,原因是默认的web-root folder为 ...

  10. 群晖系统下btfs(占用5%)和ext4文件格式的硬盘占用和选择

    1个人感觉选择ext4就可以,毕竟重要数据会设置raid1 不重要的数据也不需要快照什么的 商用除外 对于一个4t的硬盘 实际容量3726G 使用ext4可用空间3666G,群晖 占用60G大概1.6 ...