1.二叉树的最大深度
class Solution{
publc:
int maxDepth(TreeNode* root){
if(root==0)
{
return 0;
}
else
{
int m = maxDepth(root->left);
int n = maxDepth(root->right);
if(m>n)
{
return(m+1);
}
else
{
return(n+1);
}
}
}
}
也有更简单的
public int maxDepth(TreeNode root){
if(root==null) return 0;
return Math.max(maxDepth(root.left)+1,maxDepth(root.right)+1);
}
2.对称二叉树
递归方法
class Solution{
public:
bool isSymmetric(TreeNode* root){
if(root == nullptr)
return true;
return isSymmetircHelper(root->left,root->right);
}
bool isSymmetricHelper(TreeNode*left,TreeNode*right){
if(left==nullptr&&right==nullptr)
return true;
if(left==nullptr||right==nullptr||left->val!=right->val)
return false;
return isSymmetircHelper(left->left,right->right)&&isSymmetricHelper(left->right,right->left);
}
}
非递归 用到队列
class Solution{
public:
bool isSymmetric(TreeNode* root){
return check(root,roor);
}
bool check(TreeNode* Left,TreeNode* Right){
queue<TreeNode*> q;
q.push(Left);
q.push(Right);
while(!q.empty()){
Left = q.front();
q.pop();
Right = q.front();
q.pop();
if(Left==nullptr&&Right==nullptr) continue;
if(Left==nullptr||Right==nullptr||Left->val!=Right->val)
{
return false;
}
q.push(Left->left);
q.push(Right->right);
q.push(Left->right);
q.push(Right->left);
}
return true;
}
}
3.路径总和
class Solution{
public:
bool hasPathSunm(TreeNode* root, int targetSum){
if(root==nullptr) return false;
if(root->left==nullptr&&root->right==nullptr) return root->val==targetSum;
return hasPathSum(root->left,targetSum-root->val)||hasPathSum(root->right,targetSum-root->val);
}
}