uacs2024

导航

leetcode104-二叉树的最大深度

104. 二叉树的最大深度

 

这道题用递归法还是很容易的,递归的关键在于停止条件、递归函数和返回值处理。

方法一:DFS

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root==nullptr)   return 0;
        int leftCount = maxDepth(root->left);
        int rightCount = maxDepth(root->right);
        return max(leftCount,rightCount)+1;
    }
};

方法二:BFS,层次遍历。还没有复习?到树和队列,所以先记录一下

class solution {
public:
    int maxdepth(treenode* root) {
        if (root == NULL) return 0;
        int depth = 0;
        queue<treenode*> que;
        que.push(root);
        while(!que.empty()) {
            int size = que.size();
            depth++; // 记录深度,下一步是要把这一层的所有结点遍历完为止
            for (int i = 0; i < size; i++) {
                treenode* node = que.front();
                que.pop();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }
        return depth;
    }
};
/*作者:carlsun-2
链接:https://leetcode.cn/problems/maximum-depth-of-binary-tree/solution/by-carlsun-2-ojzh/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/

 

posted on 2022-09-17 19:18  ᶜʸᵃⁿ  阅读(7)  评论(0编辑  收藏  举报