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 ...
随机推荐
- LOJ P10018 数的划分 题解
每日一题 day52 打卡 Analysis 这道题直接搜索会TLE到**,但我们发现有很多没有用的状态可以删去,比如 1,1,5; 1,5,1; 5,1,1; 所以很容易想到一个优化:按不下降的顺序 ...
- WinDbg常用命令系列---||(系统状态)
||(系统状态) 简介 双竖线 ( || ) 命令将打印指定的系统或当前正在调试的所有系统的状态. 使用形式 || System 参数 System 指定要显示的系统. 如果省略此参数,将显示正在调试 ...
- pgloader 学习(八) pg 2 pg 简单demo
pg 数据到pg 数据的迁移,同时支持名称的变更 环境准备 docker-compose文件 内容偏多可以忽略部分 version: "3" services: pgloader- ...
- C#程序发送POST请求数据中+号丢失解决方案
C#程序把RSA加密后的密码发送到后台总是校验失败,用wireshark抓包检查发现POST发出的密码中的+号都变成了空格.为了正确的发送数据,要用URL转码协议进行转码. 有两个方法进行URL转码 ...
- required string parameter 'XXX'is not present 的几种情况
required string parameter 'XXX'is not present 的几种情况 情况一:原因是由于头文件类型不对,可以在MediaType中选择合适的类型,例如GET和POST ...
- debian10使用国内源安装docker以及一些使用方法
首先, 我的环境是debian, 容器是centos debian 安装添加新存储库所需的依赖项 1 sudo apt install ca-certificates curl software-pr ...
- 辨析Java方法参数中的值传递和引用传递
小方法大门道 小瓜瓜作为一个Java初学者,今天跟我说她想通过一个Java方法,将外部变量通过参数传递到方法中去,进行逻辑处理,方法执行完毕之后,再对修改过的变量进行判断处理,代码如下所示. publ ...
- 腾讯云手动搭建nginx+php-fpm并自启动
自己一点小爱好,搭建了一个小网站植物大战僵尸百科, 使用的是腾讯云,市场里的镜像不好用,所以自己手动搭建一波. centos 7 编译安装 php-7.2.11的步骤 在官网下载php-7.2.11的 ...
- tomcat启动报错java.lang.OutOfMemoryError:PermGen space解决办法
tomcat启动错误提示: 严重: Error waiting for multi-thread deployment of WAR files to completejava.util.concur ...
- 《The Boost C++ Libraries》 第一章 智能指针
Boost.SmartPointers中提供了多种智能指针,它们采用在智能指针析构时释放内存的方式,帮助管理动态分配的对象.由于析构函数在智能指针生命周期结束时被执行,所以由它管理的动态分配对象可以保 ...