另一个树的子树
思路
两个数都遍历一遍,找到一个根结点相同时,判断以这个根结点为首的二叉树是否相等
- 前序遍历
- 判断两棵树是否相同
- 对于返回值的处理是难点
bool isSameTree(struct TreeNode *p, struct TreeNode *q)
{if(p == NULL && q == NULL){return true;}if(p == NULL || q== NULL){return false;}return q->val == p->val&&isSameTree(q->left,p->left)&&isSameTree(q->right,p->right);
}bool preorderTraversal (struct TreeNode *root,struct TreeNode *t){//bool root_ret ;if(root == NULL){return false;}//根if(root->val == t->val && isSameTree(root,t)){return true;}//左bool left = preorderTraversal(root->left,t);if(left == true){return true;}//右bool right = preorderTraversal(root->right,t);return left || right;
}bool isSubtree(struct TreeNode* s, struct TreeNode* t){if(t == NULL){return true;}return preorderTraversal(s,t);
}
二叉树最大深度
思路
已知
- 左子树高度 left
- 右子树高度 right
- height = max(left , right) +1
终止条件
- 空树 return 0
/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/int maxDepth(struct TreeNode* root){if(root == NULL){return 0;}int left = maxDepth(root->left);int right = maxDepth(root->right);return (left > right ? left : right) + 1;
}