递归
树的高度
class Solution {
public :
int maxDepth ( TreeNode* root) {
if ( root == NULL )
return 0 ;
else
return max ( maxDepth ( root- > left) , maxDepth ( root- > right) ) + 1 ;
} ;
平衡树
class Solution {
public :
int getMaxDepth ( TreeNode* root) {
if ( root == NULL )
return 0 ;
return max ( getMaxDepth ( root- > left) , getMaxDepth ( root- > right) ) + 1 ;
}
bool isBalanced_multipass ( TreeNode* root) {
if ( root == NULL )
return true ;
int leftDepth = getMaxDepth ( root- > left) ;
int rightDepth = getMaxDepth ( root- > right) ;
return abs ( leftDepth - rightDepth) <= 1 && isBalanced ( root- > left) && isBalanced ( root- > right) ;
}
int maxdepth ( TreeNode* root) {
if ( root == NULL )
return 0 ;
int Lmax = maxdepth ( root- > left) ;
if ( Lmax == - 1 )
return - 1 ;
int Rmax = maxdepth ( root- > right) ;
if ( Rmax == - 1 )
return - 1 ;
if ( abs ( Lmax - Rmax) > 1 )
return - 1 ;
else
return max ( Lmax, Rmax) + 1 ;
}
bool isBalanced ( TreeNode* root) {
if ( root == NULL )
return true ;
return maxdepth ( root) != - 1 ;
}
} ;
两节点的最长路径
class Solution {
public :
int result;
int maxdepth ( TreeNode* root) {
if ( root == NULL )
return 0 ;
int L = maxdepth ( root- > left) ;
int R = maxdepth ( root- > right) ;
if ( L + R > result)
result = L + R;
return max ( L, R) + 1 ;
}
int diameterOfBinaryTree ( TreeNode* root) {
result = 0 ;
maxdepth ( root) ;
return result;
}
} ;
翻转树
class Solution {
public :
TreeNode* invertTree ( TreeNode* root) {
if ( root == NULL )
return NULL ;
TreeNode* invertedLeft = invertTree ( root- > left) ;
TreeNode* invertedRight = invertTree ( root- > right) ;
root- > left = invertedRight;
root- > right = invertedLeft;
return root;
}
} ;
归并两棵树
class Solution {
public :
TreeNode* mergeTrees ( TreeNode* root1, TreeNode* root2) {
if ( root1 == root2 && root1 == NULL )
return NULL ;
if ( root1 == NULL || root2 == NULL )
return root1 == NULL ? root2 : root1;
TreeNode* left = mergeTrees ( root1- > left, root2- > left) ;
TreeNode* right = mergeTrees ( root1- > right, root2- > right) ;
root1- > val + = root2- > val;
root1- > left = left;
root1- > right = right;
return root1;
}
} ;
判断路径和是否等于一个数
class Solution {
public :
bool hasPathSum ( TreeNode* root, int targetSum) {
if ( root == NULL )
return false ;
if ( root- > left == NULL && root- > right == NULL )
return targetSum == root- > val;
return hasPathSum ( root- > left, targetSum- root- > val) || hasPathSum ( root- > right, targetSum- root- > val) ;
}
} ;