leetcode tree相关题目小结

所使用的方法不外乎递归DFSBFS

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相关题目总结的更多相关文章

  1. [LeetCode] [链表] 相关题目总结

    刷完了LeetCode链表相关的经典题目,总结一下用到的技巧: 技巧 哑节点--哑节点可以将很多特殊case(比如:NULL或者单节点问题)转化为一般case进行统一处理,这样代码实现更加简洁,优雅 ...

  2. [LeetCode] 二叉树相关题目(不完全)

    最近在做LeetCode上面有关二叉树的题目,这篇博客仅用来记录这些题目的代码. 二叉树的题目,一般都是利用递归来解决的,因此这一类题目对理解递归很有帮助. 1.Symmetric Tree(http ...

  3. LeetCode - 排列相关题目

    1.获取全排列 https://leetcode.com/problems/permutations/submissions/ 按字典序输出: 这里用的是vector<int>,不是引用. ...

  4. Leetcode回溯相关题目Python实现

    1.46题,全排列 https://leetcode-cn.com/problems/permutations/ class Solution(object): def permute(self, n ...

  5. [LeetCode] 链表反转相关题目

    暂时接触到LeetCode上与链表反转相关的题目一共有3道,在这篇博文里面总结一下.首先要讲一下我一开始思考的误区:链表的反转,不是改变节点的位置,而是改变每一个节点next指针的指向. 下面直接看看 ...

  6. LeetCode: Palindrome 回文相关题目

    LeetCode: Palindrome 回文相关题目汇总 LeetCode: Palindrome Partitioning 解题报告 LeetCode: Palindrome Partitioni ...

  7. leetcode top 100 题目汇总

    首先表达我对leetcode网站的感谢,与高校的OJ系统相比,leetcode上面的题目更贴近工作的需要,而且支持的语言广泛.对于一些比较困难的题目,可以从讨论区中学习别人的思路,这一点很方便. 经过 ...

  8. leetcode - 位运算题目汇总(下)

    接上文leetcode - 位运算题目汇总(上),继续来切leetcode中Bit Manipulation下的题目. Bitwise AND of Numbers Range 给出一个范围,[m, ...

  9. 814. Binary Tree Pruning(leetcode) (tree traverse)

    https://leetcode.com/contest/weekly-contest-79/problems/binary-tree-pruning/ -- 814 from leetcode tr ...

随机推荐

  1. vue中代理实现方法

    vue中代理实现方法如下: const path = require('path'); function resolve(dir) { return path.join(__dirname, dir) ...

  2. [RN] React Native 使用 FlatList 实现九宫格布局 GridList

    React Native 使用 FlatList 实现九宫格布局 先看图片演示实例: 本文以图片列表为例,实现九宫格布局! 主要有两种方法: 1)方法一: 利用FlatList的 numColumns ...

  3. php7 configure: error: Cannot find OpenSSL's <evp.h> 问题解决

    开始以为是没有安装openssl, openssl-devel,安装后发现还是提示这个错误,搜索了一下evp.h,这个文件也存在.GOOGLE 了一下,在stackoverflow,找到了答案,原来是 ...

  4. 3、kafka工作流程

    一.kafka各成员 kafka: 分布式消息系统,将消息直接存入磁盘,默认保存一周. broker: 组成kafka集群的节点,之间没有主从关系,依赖zookeeper来协调,broker负责满息的 ...

  5. Hungry Canadian

    Hungry Canadian(简单dp) 具体见代码注释 #include <iostream> #include <cstdio> #include <cstring ...

  6. shell脚本编程基础知识点

    整数比较: -eq:测试两个整数是否相等:相等为真,不等为假 -ne:测试两个整数是否不等:不等为真,相等为假 -gt:测试一个数是否大于另一个数:大于为真,否则为假 -lt:测试一个数是否小于另一个 ...

  7. 打印出js对象里面的内容

    最近调试的时候遇到需要打印出js对象里面的内容,两种方式: 1.直接使用 JSON.stringify(obj) 方法把对象转成字符串,打印出来.但是因为维护的项目比较老,使用的还是ie11的ie5兼 ...

  8. 拉格朗日插值法(c++)【转载】

    摘自<c++和面向对象数值计算>,代码简洁明快,采用模板函数,通用性增强,对其中代码稍加改动 #include<iostream> #include <vector> ...

  9. 刷题记录:2018HCTF&admin

    目录 刷题记录:2018HCTF&admin 一.前言 二.正文 1.解题过程 2.解题方法 刷题记录:2018HCTF&admin 一.前言 经过一个暑假的学习,算是正经一条web狗 ...

  10. [C++] const和mutable关键字使用方法

    const 修饰的变量为常成员变量,表示此变量不能被修改赋值,并且构造函数中只能用初始化列表的方式初始化,其他初始化方式都是错误的 const 修饰的函数为常成员函数,表示此函数中只能读取成员变量,不 ...