LeetCode-tree类总结(会持续更新...)

本文主要是对leetcode中的tree类算法的总结,包含了各题的solution和常用的解决方法。

相关源码:code

此类题的常用思路:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
1. 树的遍历
2. 递归
3. 树的搜索
4. 集合数据结构
5. BST的中序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

107. Binary Tree Level Order Traversal II

Description:

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],

1
2
3
4
5
3
/ \
9 20
/ \
15 7

return its bottom-up level order traversal as:

1
2
3
4
5
[
[15,7],
[9,20],
[3]
]

解题思路:本题要求按层打印并且自底向上,故需要使用队列 ,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> q;
stack<vector<int>> tower;
if(root) q.push(root);
while(!q.empty()){
vector<int> temp;
size = q.size();
for(int i=0; i<size; i++){
TreeNode* node = q.front();
q.pop();
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
temp.push_back(root->val);
}
tower.push(temp);
}
while(!tower.empty()){
res.push_back(tower.top());
tower.pop();
}
return res;
}
};

404. Sum of Left Leaves

Description:

Find the sum of all left leaves in a given binary tree.

Example:

1
2
3
4
5
6
7
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

解题思路:使用递归,代码如下:

1
2
3
4
5
6
7
8
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(!root) return 0;
if(root->left && root->left->left==NULL && root->left->right == NULL) return root->left->val + sumOfLeftLeaves(root->right);
return sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
}
};

669. Trim a Binary Search Tree

Description:

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.

Example 1:

1
2
3
4
5
6
7
8
9
10
11
12
Input:
1
/ \
0 2
L = 1
R = 2
Output:
1
\
2

Example 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Input:
3
/ \
0 4
\
2
/
1
L = 1
R = 3
Output:
3
/
2
/
1

解题思路:本题是BST,所以要用好BST特性。本质上本题考察的是BST的遍历,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution{
public:
TreeNode* trimBST(TreeNode* root, int L, int R){
if(!root) return NULL;
if(root->val < L){
root = trimBST(root->right, L, R);
}else if(root->val > R){
root = trimBST(root->left, L, R);
}else{
root->left = trimBST(root->left, L, R);
root->left = trimBST(root->right, L, R);
}
return root;
}
};

543. Diameter of Binary Tree

Description:

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longestpath between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree

1
2
3
4
5
1
/ \
2 3
/ \
4 5

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

解题思路:属于求树高的变体,思路是使用递归方式遍历,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
if(!root) return 0;
int res = depth(root->left) + depth(root->right);
return max(res, max(diameterOfBinaryTree(root->left), diameterOfBinaryTree(root->right)));
}
int depth(TreeNode* root){
if(!root) return 0;
return 1+max(depth(root->left), depth(root->right));
}
};

437. Path Sum III

Description:

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11

解题思路:本题属于“串行递归”:因为根节点、左子节点和右节点都有可能满足题意,所以对它们要同等对待。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if(!root) return 0;
return pathSumFrom(root, sum) + pathSum(root->left,sum) + pathSum(root->right,sum);
}
int pathSumFrom(TreeNode* root, int sum){
if(!root) return 0;
return (root->val==sum ? 1 : 0) + pathSumFrom(root->left, sum - root->val) + pathSumFrom(root->right,sum-root->val);
}
};

110. Balance Binary Tree

Description:

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.

解题思路:使用搜索 的方式解决此题,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(!root) return true;
return dfsHeight(root) != -1;
}
int dfsHeight(TreeNode* root){
if(!root) return 0;
int l = dfsHeight(root->left);
if(l==-1) return -1;
int r = dfsHeight(root->right);
if(r==-1) return -1;
if(abs(l-r)>1) return -1;
return 1+max(dfsHeight(root->left), dfsHeight(root->right));
}
};

111. Minimum Depth of Binary Tree

Description:

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.

解题思路:本题是求深度的变形,重点区分含有双子节点的父节点和含有单子节点的父节点,代码如下:

1
2
3
4
5
6
7
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
return root->left == NULL || root->right == NULL ? 1+max(minDepth(root->left), minDepth(root->right)) : 1+min(minDepth(root->left), minDepth(root->right));
}
};

112. Path Sum

Description:

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.

For example:

Given the below binary tree and

1
sum = 22

,

1
2
3
4
5
6
7
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.

解题思路:递归,代码如下:

1
2
3
4
5
6
7
8
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(!root) return false;
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);
}
};

501. Find Mode in Binary Search Tree

Description:

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than or equal to the node’s key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
  • Both the left and right subtrees must also be binary search trees.

For example:
Given BST [1,null,2,2],

1
2
3
4
5
1
\
2
/
2

return [2].

Note: If a tree has more than one mode, you can return them in any order.

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
private:
vector<int> res;
public:
vector<int> findMode(TreeNode* root) {
int max, pre, cnt;
getMax(root, max=0, pre, cnt=0);
getMode(root, max, pre, cnt=0);
return res;
}
void getMax(TreeNode* root, int &max, int &pre, int &cnt){
if(!root) return;
getMax(root->left, max, pre, cnt);
getMax(root->right, max=cnt>max?cnt:max, pre=root->val, ++(cnt*=(pre==root->val)));
}
void getMode(TreeNode* root, int max, int &pre, int &cnt){
if(!root) return;
getMode(root->left, max, pre, cnt);
if(++(cnt*=(root->val==pre)) == max) res.push_back(root->val);
getMode(root->right, max, pre=root->val, cnt);
}
};

538. Convert BST to Greater Tree

Description:

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

Example:

1
2
3
4
5
6
7
8
9
Input: The root of a Binary Search Tree like this:
5
/ \
2 13
Output: The root of a Greater Tree like this:
18
/ \
20 13

解题思路:本题考察BST的中序遍历,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
private:
int sum=0;
public:
TreeNode* convertBST(TreeNode* root) {
travel(root);
return root;
}
void travel(TreeNode* root){
if(root == NULL) return;
travel(root->right);
sum += root->val;
root->val = sum;
travel(root->left);
}
};

617. Merge Two Binary Trees

Description:

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

Example 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7

Note: The merging process must start from the root nodes of both trees.

解题思路:根据题意来,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if(t1!=NULL && t2!=NULL){
t1->val += t2->val;
}else if(t1==NULL){
return t2;
}else if(t2==NULL){
return t1;
}else{
return NULL;
}
t1->left = mergeTrees(t1->left,t2->left);
t1->right = mergeTrees(t1->right,t2->right);
return t1;
}
};

637. Average of Levels in Binary Tree

Description:

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Example 1:

1
2
3
4
5
6
7
8
9
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].

Note:

  1. The range of node’s value is in the range of 32-bit signed integer.

解题思路:对树进行分层操作,自然而然会想到使用集合数据结构:队列 ,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> res;
queue<TreeNode*> q;
if(root) q.push(root);
while(!q.empty()){
int s = q.size();
int temp = 0;
for(int i=0; i<s; i++){
TreeNode* node = q.front();
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
temp += node->val;
q.pop();
}
res.push_back(temp/(double)s);
}
return res;
}
};

108. Convert Sorted Array to Binary Search Tree

Description:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

解题思路:根据BST特点解题,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.size()==0) return NULL;
if(nums.size()==1) return new TreeNode(nums[0]);
int mid = nums.size()/2;
TreeNode* root = new TreeNode(nums[mid]);
vector<int> l(nums.begin(), nums.begin()+mid);
vector<int> r(nums.begin()+mid+1,nums.end());
root->left = sortedArrayToBST(l);
root->right = sortedArrayToBST(r);
return root;
}
};

235. Lowest Common Ancestor of a Binary Search Tree

Description:

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

1
2
3
4
5
6
7
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

解题思路:结合BST特点,代码如下:

1
2
3
4
5
6
7
8
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root->val < min(p->val, q->val)) return lowestCommonAncestor(root->right, p, q);
if(root->val > max(p->val, q->val)) return lowestCommonAncestor(root->left, p, q);
return root;
}
};

653. Two Sum IV - Input is a BST

Description:

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1:

1
2
3
4
5
6
7
8
9
10
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True

Example 2:

1
2
3
4
5
6
7
8
9
10
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False

解题思路:结合BST特点,将BST转化为升序数组,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
private:
vector<int> res;
public:
bool findTarget(TreeNode* root, int k) {
travel(root);
int i=0;
int j=res.size()-1;
while(i<j){
int sum = res[i]+res[j];
if(sum > k){
j--;
}else if(sum < k){
i++;
}else{
return true;
}
}
return false;
}
void travel(TreeNode* root){
if(root == NULL) return;
travel(root->left);
res.push_back(root->val);
travel(root->right);
}
};

101. Symmetric Tree

Description:

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
3
4
5
1
/ \
2 2
/ \ / \
3 4 4 3

But the following [1,2,2,null,3,null,3] is not:

1
2
3
4
5
1
/ \
2 2
\ \
3 3

Note:
Bonus points if you could solve it both recursively and iteratively.

解题思路:代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
bool isSymmetric(TreeNode* root) {
return root==NULL || isSymmetricHelp(root->left, root->right);
}
bool isSymmetricHelp(TreeNode* l, TreeNode* r){
if(l==NULL || r==NULL) return l==r;
if(l->val != r->val) return false;
return isSymmetricHelp(l->left, r->right) && isSymmetricHelp(l->right, r->left);
}
};

563. Binary Tree Tilt

Description:

Given a binary tree, return the tilt of the whole tree.

The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.

The tilt of the whole tree is defined as the sum of all nodes’ tilt.

Example:

1
2
3
4
5
6
7
8
9
10
Input:
1
/ \
2 3
Output: 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1

Note:

  1. The sum of node values in any subtree won’t exceed the range of 32-bit integer.
  2. All the tilt values won’t exceed the range of 32-bit integer.

解题思路:代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int result = 0;
int findTilt(TreeNode* root) {
postOrder(root);
return result;
}
int postOrder(TreeNode* root){
if(!root) return 0;
int l = postOrder(root->left);
int r = postOrder(root->right);
result += abs(l-r);
return l+r+root->val;
}
};

572. Subtree of Another Tree

Description:

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.

Example 1:
Given tree s:

1
2
3
4
5
3
/ \
4 5
/ \
1 2
1
2
3
4
/ \
1 2

true

Example 2:
Given tree s:

1
2
3
4
5
6
7
3
/ \
4 5
/ \
1 2
/
0
1
2
3
4
/ \
1 2

false

解题思路:判断高度,判断是否相同,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
vector<TreeNode*> nodes;
bool isSubtree(TreeNode* s, TreeNode* t) {
if(!t && !s){
return true;
}
if(!t || !s){
return false;
}
getDepth(s, getDepth(t, -1));
for(TreeNode* n : nodes){
if(identical(n, t)){
return true;
}
}
return false;
}
int getDepth(TreeNode* r, int d){
if(!r) return 0;
int depth = max(getDepth(r->left, d), getDepth(r->right, d)) + 1;
if(depth == d) nodes.push_back(r);
return depth;
}
bool identical(TreeNode* s, TreeNode* t){
if(!s && !t) return true;
if(!s || !t || s->val!=t->val) return false;
return identical(s->left, t->left) && identical(s->right, t->right);
}
};

671. Second Minimum Node In a Binary Tree

Descripiton:

Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node’s value is the smaller value among its two sub-nodes.

Given such a binary tree, you need to output the second minimum value in the set made of all the nodes’ value in the whole tree.

If no such second minimum value exists, output -1 instead.

Example 1:

1
2
3
4
5
6
7
8
9
Input:
2
/ \
2 5
/ \
5 7
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.

Example 2:

1
2
3
4
5
6
7
Input:
2
/ \
2 2
Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
int findSecondMinimumValue(TreeNode* root) {
if(root->left){
if(root->left->val < root->right->val){
int l = findSecondMinimumValue(root->left);
if(l==-1) return root->right->val;
return min(l, root->right->val);
}else if(root->left->val > root->right->val){
int r = findSecondMinimumValue(root->right);
if(r==-1) return root->left->val;
return min(r, root->left->val);
}else{
int l = findSecondMinimumValue(root->left);
int r = findSecondMinimumValue(root->right);
if(l==-1) return r;
if(r==-1) return l;
return min(l, r);
}
}else{
return -1;
}
return -1;
}
};

687. Longest Univalue Path

Description:

Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.

Note: The length of path between two nodes is represented by the number of edges between them.

Example 1:

Input:

1
2
3
4
5
5
/ \
4 5
/ \ \
1 1 5

Output:

1
2

Example 2:

Input:

1
2
3
4
5
1
/ \
4 5
/ \ \
4 4 5

Output:

1
2

Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

解题思路:本题需要使用搜索 ,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
int lup = 0;
if(root) dfs(root, lup);
return lup;
}
private:
int dfs(TreeNode* node, int& lup) {
int l = node->left ? dfs(node->left, lup) : 0;
int r = node->right ? dfs(node->right, lup) : 0;
int resl = node->left && node->left->val == node->val ? l + 1 : 0;
int resr = node->right && node->right->val == node->val ? r + 1 : 0;
lup = max(lup, resl + resr);
return max(resl, resr);
}
};