【问题】输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

【思路】递归解法:一般和深度有关的我们都可以使用dfs算法,然后使用一个res用于记录深度,每次递归到叶节点,将res和max进行比较,将最大的值存入max变量中,结束递归!这样我们就可以找到每一条路径深度最大的哪一个路径了!

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

第二种使用非递归的思路,我们都知道层次遍历,每次都是遍历完上一层才会去下一层遍历。因此,我们可以对层次遍历加以修改!设置一个depth变量,如果遍历完一层,则让depth++。层次遍历需要队列的辅助!

/*
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*> que;
        que.push(pRoot);
        int depth = 0;
        while(!que.empty()){
            int size = que.size();
            depth++;
            while(size--){
                TreeNode* tmp = que.front();
                que.pop();
                if(tmp->left) que.push(tmp->left);
                if(tmp->right) que.push(tmp->right);
            }
        }
        return depth;
    }
};