226.翻转二叉树
思路:前序遍历
代码:
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root!=NULL){
swap(root->left,root->right);
invertTree(root->left);
invertTree(root->right);
}
return root;
}
};
101. 对称二叉树
思路:左右两棵子树同时遍历
代码:
class Solution {
public:
bool compare(TreeNode* left,TreeNode* right){
if(left==NULL&&right!=NULL) return false;
else if(left!=NULL&&right==NULL) return false;
else if(left==NULL&&right==NULL) return true;
else if(left->val!=right->val) return false;
bool outside=compare(left->left,right->right);
bool inside=compare(left->right,right->left);
bool isSame=inside&&outside;
return isSame;
}
bool isSymmetric(TreeNode* root) {
if(root==NULL)
return true;
return compare(root->left,root->right);
}
};
104.二叉树的最大深度
思路:后序遍历,计算最大高度
代码:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL) return 0;
int leftdep=maxDepth(root->left);
int rightdep=maxDepth(root->right);
return max(leftdep,rightdep)+1;
}
};
111.二叉树的最小深度
思路:和求最大深度大致相同,不过要注意判断是否是叶子结点
代码:
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
int leftdep=minDepth(root->left);
int rightdep=minDepth(root->right);
if(root->left!=NULL&&root->right==NULL)
return leftdep+1;
else if(root->left==NULL&&root->right!=NULL)
return rightdep+1;
else
return min(leftdep,rightdep)+1;
}
};
标签:right,return,第十四天,二叉树,深度,NULL,root,left
From: https://blog.csdn.net/dtgfhfd/article/details/140473440