递归
一棵树要么是空树,要么有两个指针,每个指针指向一棵树。树是一种递归结构,很多树的问题可以使用递归来处理。
1. 树的高度
104. Maximum Depth of Binary Tree (Easy)
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
2. 平衡树
110. Balanced Binary Tree (Easy)
3
/ \
9 20
/ \
15 7
平衡树左右子树高度差都小于等于 1
class Solution {
public:
bool result = true;
bool isBalanced(TreeNode* root) {
if(root == NULL) return true;
maxDepth(root);
return result;
}
int maxDepth(TreeNode* root){
if(root == NULL) return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
if(abs(left-right)>1)
result = false;
return max(left, right)+1;
}
};
3. 两节点的最长路径
543. Diameter of Binary Tree (Easy)
Input:
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
class Solution {
public:
int maxCount = 0;
int diameterOfBinaryTree(TreeNode* root) {
maxDepth(root);
return maxCount;
}
int maxDepth(TreeNode* root){
if(root == NULL) return 0;
int left = maxDepth(root->left); //左分支节点深度
int right = maxDepth(root->right); //右分支节点深度
maxCount = max(maxCount, left + right);
return max(left, right) + 1;
}
};
4. 翻转树
226. Invert Binary Tree (Easy)
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return NULL;
TreeNode* right = root->right;
root->right = invertTree(root->left);
root->left = invertTree(right);
return root;
}
};
5. 归并两棵树
617. Merge Two Binary Trees (Easy)
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
3
/ \
4 5
/ \ \
5 4 7
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if(t1 == NULL) return t2;
if(t2 == NULL) return t1;
t1->val += t2->val;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
return t1;
}
};
6. 判断路径和是否等于一个数
Leetcdoe : 112. Path Sum (Easy)
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.
路径和定义为从 root 到 leaf 的所有节点的和。
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == NULL) return false;
sum -= root->val;
if((root->left==NULL)&& (root->right==NULL))
return (sum==0);
bool left = hasPathSum(root->left, sum);
bool right = hasPathSum(root->right, sum);
return left||right;
}
};
7. 统计路径和等于一个数的路径数量
437. Path Sum III (Easy)
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
路径不一定以 root 开头,也不一定以 leaf 结尾,但是必须连续。
class Solution {
public:
int helper(TreeNode* root, int sum) {
if(root == NULL) return 0;
sum -= root->val;
return (sum==0 ? 1 : 0) + helper(root->left, sum) + helper(root->right, sum);
}
int pathSum(TreeNode* root, int sum){
if(root==NULL) return 0;
return helper(root, sum) + pathSum(root->left, sum) + pathSum(root->