leetcode tree相关题目总结
leetcode tree相关题目小结
所使用的方法不外乎递归,DFS,BFS。
1. 题100 Same Tree
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value
Example 1:
Input:
1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input:
1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input:
1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
这道题让我们判断两个树是否相同。解法就是递归,判断两个树的子树是否相同。
/**
* 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:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (p == NULL || q == NULL)
{
return (p == q);
}
if (p->val == q->val)
{
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
else
{
return false;
}
}
};
2. 题101 Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
这题要求判断树是否对称,即判断左子树与右子树是否相同,解法与题100类似。
/**
* 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:
bool isSymmetric(TreeNode* root) {
if (root == NULL)
{
return true;
}
else
{
return isSymmetr(root->left, root->right);
}
}
bool isSymmetr(TreeNode* left, TreeNode* right)
{
if (left == NULL || right == NULL)
{
return (left == right);
}
if (left->val == right->val)
{
return isSymmetr(left->left, right->right) && isSymmetr(right->left, left->right);
}
else
{
return false;
}
}
};
3. 题104 Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
这题求树的最大深度,有两种解法。
解法一:广度优先搜索
/**
* 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 maxDepth(TreeNode* root) {
if (root == NULL)
{
return 0;
}
queue<TreeNode*> q;
q.push(root);
int depth = 0;
while(!q.empty())
{
++depth;
for (int i = 0, n = q.size(); i < n; ++i)
{
TreeNode *p = q.front();
q.pop();
if (p->left != NULL)
{
q.push(p->left);
}
if (p->right != NULL)
{
q.push(p->right);
}
}
}
return depth;
}
};
解法二:深度优先搜索
计算左子树和右子树的深度,取较大者 + 1
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL)
{
return 0;
}
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
4. 题111. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
这题要求求解树的最小高度.
解法一:
自底向上
与上面求最大高度类似,递归求解子树的最小高度,再加一即得到最终树的最小高度,但要注意的是,如果任一子树为NULL,那么树的最小高度不是 0 + 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 minDepth(TreeNode* root) {
if (root == NULL)
{
return 0;
}
int left = minDepth(root->left);
int right = minDepth(root->right);
return ((min(left, right) == 0) ? max(left, right) : min(left, right)) + 1;
}
}
解法二:
自顶向下
采用类似广度优先搜索的办法,自上而下层层搜索,直到某一层的某个节点没有子树,即为最小高度
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL)
{
return 0;
}
queue<TreeNode *> q;
q.push(root);
int mindepth = 0;
while(!q.empty())
{
++mindepth;
for (int i = 0, n = q.size(); i < n; ++i)
{
TreeNode* p = q.front();
q.pop();
if (p->left != NULL)
{
q.push(p->left);
}
if (p->right != NULL)
{
q.push(p->right);
}
if (p->left == p->right) // 判断是否为叶子, left = right = NULL
{
return mindepth;
}
}
}
return 0;
}
}
5. 题110 Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
本题要求判断所给的树是否为高度平衡树,所谓高度平衡树,即所有节点的左子树和右子树的深度差别不超过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:
bool isBalanced(TreeNode* root) {
if (root == NULL)
{
return true;
}
return (abs(depth(root->left) - depth(root->right)) <= 1) && isBalanced(root->left) && isBalanced(root->right);
}
// 计算高度
int depth(TreeNode* root) {
if (root == NULL)
{
return 0;
}
return max(depth(root->left), depth(root->right)) + 1;
}
}
6. 题107 Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
本题要求给出树自底向上的层序遍历
解法:广度优先搜索
/**
* 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<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> rv;
if (root == NULL)
{
return rv;
}
queue<TreeNode *> q;
q.push(root);
while(!q.empty())
{
vector<int> v;
for (int i = 0, n = q.size(); i < n; ++i)
{
TreeNode *p = q.front();
q.pop();
v.push_back(p->val);
if (p->left != NULL)
{
q.push(p->left);
}
if (p->right != NULL)
{
q.push(p->right);
}
}
rv.push_back(v);
}
reverse(rv.begin(), rv.end());
return rv;
}
}
7. 题112 Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
本题要求判断树中是否存在一条根到叶子的路径是的路径上的所有节点和为sum。依然是递归解法,问题可分解为子树中是否存在一条路径使得和为sum - 当前节点的值
解法:
/**
* 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:
bool hasPathSum(TreeNode* root, int sum) {
if (root == NULL)
{
return false;0
}
if ((root->val == sum) && (root->left == NULL) && (root->right == NULL))
{
return true;
}
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
}
leetcode tree相关题目总结的更多相关文章
- [LeetCode] [链表] 相关题目总结
刷完了LeetCode链表相关的经典题目,总结一下用到的技巧: 技巧 哑节点--哑节点可以将很多特殊case(比如:NULL或者单节点问题)转化为一般case进行统一处理,这样代码实现更加简洁,优雅 ...
- [LeetCode] 二叉树相关题目(不完全)
最近在做LeetCode上面有关二叉树的题目,这篇博客仅用来记录这些题目的代码. 二叉树的题目,一般都是利用递归来解决的,因此这一类题目对理解递归很有帮助. 1.Symmetric Tree(http ...
- LeetCode - 排列相关题目
1.获取全排列 https://leetcode.com/problems/permutations/submissions/ 按字典序输出: 这里用的是vector<int>,不是引用. ...
- Leetcode回溯相关题目Python实现
1.46题,全排列 https://leetcode-cn.com/problems/permutations/ class Solution(object): def permute(self, n ...
- [LeetCode] 链表反转相关题目
暂时接触到LeetCode上与链表反转相关的题目一共有3道,在这篇博文里面总结一下.首先要讲一下我一开始思考的误区:链表的反转,不是改变节点的位置,而是改变每一个节点next指针的指向. 下面直接看看 ...
- LeetCode: Palindrome 回文相关题目
LeetCode: Palindrome 回文相关题目汇总 LeetCode: Palindrome Partitioning 解题报告 LeetCode: Palindrome Partitioni ...
- leetcode top 100 题目汇总
首先表达我对leetcode网站的感谢,与高校的OJ系统相比,leetcode上面的题目更贴近工作的需要,而且支持的语言广泛.对于一些比较困难的题目,可以从讨论区中学习别人的思路,这一点很方便. 经过 ...
- leetcode - 位运算题目汇总(下)
接上文leetcode - 位运算题目汇总(上),继续来切leetcode中Bit Manipulation下的题目. Bitwise AND of Numbers Range 给出一个范围,[m, ...
- 814. Binary Tree Pruning(leetcode) (tree traverse)
https://leetcode.com/contest/weekly-contest-79/problems/binary-tree-pruning/ -- 814 from leetcode tr ...
随机推荐
- 《OKR工作法》–让所有人承担自己的职责
<OKR工作法>中提到了一个创业故事,TeaBee,创业的目标是让喜欢喝茶的人喝到好茶. 创业初期作为首席执行官的汉娜和作为总裁的杰克就在将茶叶提供给餐厅还是餐厅供应商上产生了分歧,随后他 ...
- 奶牛抗议 DP 树状数组
奶牛抗议 DP 树状数组 USACO的题太猛了 容易想到\(DP\),设\(f[i]\)表示为在第\(i\)位时方案数,转移方程: \[ f[i]=\sum f[j]\;(j< i,sum[i] ...
- 阿里云域名注册详解与Github绑定
关注我,每天都有优质技术文章推送,工作,学习累了的时候放松一下自己. 本篇文章同步微信公众号 欢迎大家关注我的微信公众号:「醉翁猫咪」 今教一篇如何注册域名,拥有自己的域名是不是很爽呢?答案是是的,那 ...
- P1270 “访问”美术馆——不太一样的树形DP
P1270 “访问”美术馆 dfs读入,存图有点像线段树: 在枚举时间时,要减去走这条边的代价: #include<cstdio> #include<cstring> #inc ...
- centos7安装sql-server2017
1. 关闭selinux Vim /etc/selinux/conf 将selinux=enable 改成selinux=disabled 2. 清空/关闭iptables策略 Iptables ...
- Fiddler导出JMX文件配置
(1)安装fiddler jmeter(免安装) 注意事项!fiddler版本必须在v4.6.2以上(插件支持的是4.6版本), jmeter版本最好在v3.0以上,版本太低容易导致导出不成功 这里我 ...
- 城东C位之路!探秘三线楼市板块崛起3大核心基因
等着咧!伍家篇什么时候出?这就出. 城东C位之路!- 诸葛磊 好几个粉丝已经在催了,诸葛磊决定改变下写作策略,伍家岗篇分版块用小篇幅来写,这样文章不至于太长,否则又是一篇洋洋洒洒上万字的文章,粉丝看着 ...
- 创业小记:ALL IN才是迈出创业第一步的关键
对于创业而言,能卖出这创业第一步的,大多都经过了长期反复的心理拷问与折磨. 因为当你迈出创业的那一步,你可能需要面对的是毫无收入保障的生活,以及后果自负的结局. ALL IN才是迈出创业第一步的关键( ...
- 监控指标 TP99 TP999 含义
TP=Top Percentile,Top百分数,是一个统计学里的术语,与平均数.中位数都是一类. TP50.TP90和TP99等指标常用于系统性能监控场景,指高于50%.90%.99%等百分线的情况 ...
- tensorflow到底难不难写
发信人: xhsoldier01 (风大人), 信区: ITExpress 标 题: Re: 没有GPU,tensorflow,AI公司都得死掉 发信站: 水木社区 (Thu Oct 10 20:25 ...