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 ...
随机推荐
- learning java Encoder and Decoder
import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingExcep ...
- GUI引发的一场脑部大战|wine、wsl、mono、gtk、qt
没写完不想写了,先发布吧,这就是一个引子. 在春天种下一颗种子---- GUI引发的一场脑部大战|wine.wsl.mono.gtk.qt 思路开拓了,方法一下子就来了 wine可以运行大部分Wind ...
- Shell的语法
Shell的语法: 变量:字符串.数字.环境和参数: 条件:shell中的布尔值: 程序控制:if.elif.for.while.until.case: 命令列表: 函数: Shell内置命令: 获取 ...
- Linux 磁盘格式化、检验、挂载
分区完毕之后自然要进行文件系统的格式化.格式化命令mkfs(make file system)这个命令.这是个综合命令,它会去调用正确的文件系统格式化工具软件. 磁盘格式化 mkfs mke2fs m ...
- js - 总结一下条件语句优化
[笔记] // 简单的语句用三目运算符也可以的(除了需要return的) 1 == 1 ? console.log('执行了...1') : console.log(); 1 == 2 ? conso ...
- Mysql创建测试大量测试数据
修改mysql配置 max_heap_table_size=4000M innodb_flush_log_at_trx_commit=0sync_binlog=500 创建测试数据库 create d ...
- Oracle系列七 子查询
子查询语法 SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table); 子查询 (内查询) 在 ...
- Sword 计算机内存对齐
内存对齐理论 a.数据的对齐(alignment) 指数据的地址和由硬件条件决定的内存块大小之间的关系.一个变量的地址是它大小的倍数的时候,这就叫做自然对齐(naturally aligned). 例 ...
- 【Git】The authenticity of host '192.168.1.1 (192.168.1.1)' can't be established.
背景,在服务器用www用户身份 执行拉取命令报错 sudo -u www git pull 原因分析: 在新生成密钥之后,在.ssh文件夹中少了known_hosts文件 解决办法: Are you ...
- 如何用谷歌浏览器导出一个https网站的数字证书
HTTPS加密是互联网安全建设的基础,百度.淘宝.天猫等越来越多互联网巨头启用全站HTTPS,也带动了更多网站加入HTTPS加密的行列.普通用户也逐渐明白HTTPS比HTTP更安全,访问网银.购物等重 ...