111. 二叉树的最小深度
class Solution {
public :
int minDepth ( TreeNode* root) {
if ( ! root) return 0 ;
int left = minDepth ( root-> left) ;
int right = minDepth ( root-> right) ;
if ( ! root-> left ) return right + 1 ;
else if ( ! root-> right ) return left + 1 ;
else return min ( left, right) + 1 ;
}
} ;
226. 翻转二叉树
代码
class Solution {
public :
TreeNode* invertTree ( TreeNode* root) {
if ( root == nullptr ) return nullptr ;
swap ( root-> left, root-> right) ;
invertTree ( root-> left) ;
invertTree ( root-> right) ;
return root;
}
} ;
101. 对称二叉树
代码
class Solution {
public :
bool isSymmetric ( TreeNode* root) {
return isMirrow ( root, root) ;
}
bool isMirrow ( TreeNode* left, TreeNode* right) {
if ( left == nullptr && right == nullptr ) return true ;
if ( left == nullptr && right != nullptr ) return false ;
if ( left != nullptr && right == nullptr ) return false ;
if ( left-> val != right-> val) return false ;
return isMirrow ( left-> left, right-> right) && isMirrow ( left-> right, right-> left) ;
}
} ;