JZ55 二叉树的深度

暴搜:两种个思路:DFS和BFS

DFS:

里面有个容易误会的地方:每次迭代+1,不是针对子叶来说的,而是针对当前点来说的,由于遍历是自底向上的,因此当前遍历到的点对于已经遍历到的点来说就是根,因此深度+1.

class Solution {
public:
    int TreeDepth(TreeNode* pRoot) {
        if(pRoot == nullptr) return 0;
        return max(TreeDepth(pRoot->left), TreeDepth(pRoot->right)) + 1;
    }
};

BFS:

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    int TreeDepth(TreeNode* pRoot) {
        if(pRoot == nullptr) return 0;

        queue<TreeNode*> q;
        q.push(pRoot);

        int res = 0;
        while(!q.empty()) {
            int n = q.size();
            // 遍历当前层的每个点
            for(int i = 0; i < n; i ++ ){
                TreeNode *node = q.front();
                q.pop();
                if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);
            }
            res ++;
        }
        return res;

    }
};

 

posted @ 2023-07-01 15:48  luxiayuai  阅读(48)  评论(0)    收藏  举报