层序遍历,如果有一个节点没有儿子节点,就输出它
class Solution {
public:
int run(TreeNode *root) {
if(root==NULL)return 0;
int ans=1;
queue<TreeNode*>q;
q.push(root);
while(!q.empty())
{
int size=q.size();
while(size--)
{
TreeNode*top=q.front();
q.pop();
if(top->left)q.push(top->left);
if(top->right)q.push(top->right);
if(!top->left&&!top->right)return ans;
}
ans++;
}
return ans;
}
};
网友评论