Invert Binary Tree(翻转二叉树)
struct TreeNode* invertTree(struct TreeNode* root) {
if(root == NULL)
return NULL;
struct TreeNode* left = root->left;
root->left = invertTree(root->right);
root->right = invertTree(left);
return root;
}
Maximum Depth of Binary Tree
int maxDepth(struct TreeNode* root) {
if(root == NULL)
return 0;
if(root->left==NULL&&NULL==root->right)
return 1;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return left>right ? (left+1):(right+1);
}
ps:不单独赋值left right 容易超时
Validate Binary Search Tree
bool helper(struct TreeNode* root, int* lower_bound, int* upper_bound) {
if(root == NULL) return true;
int lower_bound_left, upper_bound_left, lower_bound_right, upper_bound_right;
bool bst_left = helper(root->left, &lower_bound_left, &upper_bound_left);
bool bst_right = helper(root->right, &lower_bound_right, &upper_bound_right);
if((root->right && root->val >= lower_bound_right) || (root->left && root->val <= upper_bound_left))
return false;
*upper_bound = root->right == NULL ? root->val : upper_bound_right;
*lower_bound = root->left == NULL ? root->val : lower_bound_left;
return bst_left && bst_right;
}
bool isValidBST(struct TreeNode* root) {
int lower_bound, upper_bound;
return helper(root, &lower_bound, &upper_bound);
}
ps:重点在于所有子节点和祖先节点的大小关系要一直保持
Path Sum
bool hasPathSum(struct TreeNode* root, int sum) {
if(root == NULL)
return false;
if(root->left==NULL&&root->right==NULL)
return sum==root->val;
return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val);
}