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
classSolution{
public:
TreeNode* trimBST(TreeNode* root, int L, int R){
if(!root) returnNULL;
if(root->val < L){
root = trimBST(root->right, L, R);
}elseif(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.
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.
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
classSolution {
private:
int sum=0;
public:
TreeNode* convertBST(TreeNode* root){
travel(root);
return root;
}
voidtravel(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
classSolution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2){
if(t1!=NULL && t2!=NULL){
t1->val += t2->val;
}elseif(t1==NULL){
return t2;
}elseif(t2==NULL){
return t1;
}else{
returnNULL;
}
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:
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
classSolution {
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
classSolution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums){
if(nums.size()==0) returnNULL;
if(nums.size()==1) returnnew 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.
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:
The sum of node values in any subtree won’t exceed the range of 32-bit integer.
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
classSolution {
public:
int result = 0;
intfindTilt(TreeNode* root){
postOrder(root);
return result;
}
intpostOrder(TreeNode* root){
if(!root) return0;
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
classSolution {
public:
vector<TreeNode*> nodes;
boolisSubtree(TreeNode* s, TreeNode* t){
if(!t && !s){
returntrue;
}
if(!t || !s){
returnfalse;
}
getDepth(s, getDepth(t, -1));
for(TreeNode* n : nodes){
if(identical(n, t)){
returntrue;
}
}
returnfalse;
}
intgetDepth(TreeNode* r, int d){
if(!r) return0;
int depth = max(getDepth(r->left, d), getDepth(r->right, d)) + 1;
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
classSolution {
public:
intfindSecondMinimumValue(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);
}elseif(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
classSolution {
public:
intlongestUnivaluePath(TreeNode* root){
int lup = 0;
if(root) dfs(root, lup);
return lup;
}
private:
intdfs(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;