The sword refers to the depth of the offer 54 binary tree

Use DFS to solve

    int maxDepth(TreeNode* root) {
    
    
 
       //DFS深度遍历
       if(root==NULL)
            return 0;
        int left=maxDepth(root->left);
        int right=maxDepth(root->right);

        //找到
        return (left>right)?left+1:right+1;

Use BFS to solve

Layer sequence traversal, counter +1 for each layer

    int maxDepth(TreeNode* root) {
    
    
        //BFS   广度遍历
        deque<TreeNode*> que;
        if(root==NULL)
            return 0;
        que.push_back(root);
        int depth=0;
        while(!que.empty())
        {
    
    
            depth++;
            int count=que.size();   //记录每层的数目

            while(count--)
            {
    
                
                TreeNode* tmp=que.front();
                que.pop_front();
                if(tmp->left!=NULL)
                    que.push_back(tmp->left);
                if(tmp->right!=NULL)
                    que.push_back(tmp->right);
            }
        }
        return depth;
    }
};

Guess you like

Origin blog.csdn.net/ALITAAAA/article/details/115026777