LeetCode112
寻找一条从根节点到树节点的路径,要求之和为指定的数字。
bool hasPathSum(TreeNode *root, int sum) {
if (root == NULL) return false;
if (root->val == sum && root->left == NULL && root->right == NULL) return true;
return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
}
LeetCode100
判断2个树是否相同
bool isSameTree(TreeNode *p, TreeNode *q) {
if (p == NULL || q == NULL) return (p == q);
return (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
}
LeetCode101
判断2个树是否对称
bool isSymmetric(TreeNode *root) {
if (!root) return true;
return helper(root->left, root->right);
}
bool helper(TreeNode* p, TreeNode* q) {
if (!p && !q) {
return true;
} else if (!p || !q) {
return false;
}
if (p->val != q->val) {
return false;
}
return helper(p->left,q->right) && helper(p->right, q->left);
}