leetcode tree相关题目总结

时间:2024-08-30 16:33:41

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);
}
}