文章
7
粉丝
0
获赞
0
访问
376
1.采用后序遍历的方式,遍历每一个节点,先判断有没有左右子树,若有,则将其与自己的左子树的最右下的节点相减,和自己的右子树的最左下的节点相减,比较这两个数,若相等则+1
2.
int getRightMinDist(TreeNode *root) {
TreeNode *p = root->right;
while (p->left != NULL) {
p = p->left;
}
return abs(root->val - p->val);
}
int countNodes(TreeNode *root) {
if (root == NULL) {
return 0;
}
int count = 0;
// 递归遍历左子树
count += countNodes(root->left);
// 递归遍历右子树
count += countNodes(root->right);
// 判断当前节点是否同时有左右子树
if (root->left != NULL && root->right != NULL) {
int leftDist = getLeftMinDist(root);
int rightDist = getRightMinDist(root);
if (leftDist == rightDist) {
...
登录后发布评论
暂无评论,来抢沙发