- 求树的最大深度
- 对称二叉树
- 路径总和
1思路,自顶向下:
int answer; // don't forget to initialize answer before call maximum_depth
void maximum_depth(TreeNode* root, int depth) {//传参:1根节点 2根节点深度(1)
if (!root) {
return;
}
if (!root->left && !root->right) {//节点为叶节点时执行
answer = max(answer, depth);
}
maximum_depth(root->left, depth + 1);
maximum_depth(root->right, depth + 1);
}
思路,自底向上:
int maximum_depth(TreeNode* root) {
if (!root) {
return 0; // return 0 for null node
}
int left_depth = maximum_depth(root->left);
int right_depth = maximum_depth(root->right);
return max(left_depth, right_depth) + 1; // return depth of the subtree rooted at root
}
PS:这种思路好理解吧,求根节点的深度,只需要求左子树和右子树的深度最大值+1。
2思路,递归(详见注释):
/**
* 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) {
return isMirror(root,root);
}
private:
bool isMirror(TreeNode* t1, TreeNode* t2){
if(t1 == nullptr && t2 == nullptr) return true;//都为空,不用比返回true
if(t1 == nullptr || t2 == nullptr) return false;//一个为空,一个不为空,不用比返回false
return (t1->val == t2->val)
&& isMirror(t1->right, t2->left)
&& isMirror(t1->left, t2->right);//两个都不为空,比较它们的值,并且比较它们的子树节点是否镜像
}
};
思路,迭代(和上面类似,只不过用queue实现):
/**
* 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) {
queue<TreeNode*>q;
q.push(root);
q.push(root);
while(!q.empty()){
TreeNode* t1 = q.front();q.pop();
TreeNode* t2 = q.front();q.pop();
if(t1 == nullptr && t2 == nullptr) continue;
if(t1 == nullptr || t2 == nullptr) return false;
if(t1->val != t2->val) return false;
q.push(t1->left);
q.push(t2->right);
q.push(t1->right);
q.push(t2->left);
}
return true;
}
};
3思路,DFS
/**
* 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 DFS(TreeNode* root, int sum){
if(root == NULL){
return false;
}
if(!root->left &&!root->right){
if(root->val == sum){
return true;
}
return false;//到叶子节点,val!= sum ,直接return false
}
return (DFS(root->left, sum-root->val) || DFS(root->right, sum -root->val));
}
bool hasPathSum(TreeNode* root, int sum) {
return DFS(root, 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;
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);
}
};