Minimum-depth-of-binary-tree

2019-05-30  本文已影响0人  DaiMorph

层序遍历,如果有一个节点没有儿子节点,就输出它

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;
    }
};
上一篇下一篇

猜你喜欢

热点阅读