【剑指Offer-55-I】二叉树的深度

问题

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

解答1:前序遍历+回溯

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root) return 0;
        res = max(res, ++ level);
        maxDepth(root->left);
        maxDepth(root->right);
        level--;
        return res;
    }
private:
    int res = 0, level = 0;
};

解答2:后序遍历递归

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root) return 0;
        return max(maxDepth(root->left), maxDepth(root->right)) + 1; // 左右子树的最大深度+1以当前节点为根的树深度
    }
};

解答3:后序遍历迭代

class Solution {
public:
    int maxDepth(TreeNode* root) {
        int res = 0;
        stack<TreeNode*> s;
        TreeNode* lastVisit;
        if (root) s.push(root);
        while (!s.empty()) {
            res = max(res, (int)s.size());
            TreeNode* cur = s.top();
            if (cur->left && cur->left != lastVisit && cur->right != lastVisit)
                s.push(cur->left);
            else if (cur->right && cur->right != lastVisit)
                s.push(cur->right);
            else {
                lastVisit = cur;
                s.pop();
            }
        }
        return res;
    }
};

重点思路

这里使用栈容量表示当前节点所在的深度。前序和中序遍历不能使用栈容量表示的原因是,在遍历右子树时,根节点已输出,此时栈容量等于当前节点深度-1。

解答4:层序遍历递归

class Solution {
public:
    int maxDepth(TreeNode* root) {
        levelOrder(root, 1);
        return res;
    }
private:
    int res = 0;
    void levelOrder(TreeNode* root, int level) {
        if (!root) return;
        res = max(res, level);
        levelOrder(root->left, level + 1);
        levelOrder(root->right, level + 1);
    }
};

重点思路

这个就是把前序遍历+回溯中的全局变量cnt变为局部变量level,所以不需要level--之类的回溯操作。(层序的递归方法其实就是前序再加一个level限制)。

解答5:层序遍历迭代

class Solution {
public:
    int maxDepth(TreeNode* root) {
        int res = 0;
        queue<TreeNode*> q;
        if (root) q.push(root);
        while (!q.empty()) {
            int n = q.size();
            for (int i = 0; i < n; i++) {
                TreeNode* cur = q.front(); q.pop();
                if (cur->left) q.push(cur->left);
                if (cur->right) q.push(cur->right);
            }
            res++;
        }
        return res;
    }
};
posted @ 2021-03-06 13:42  tmpUser  阅读(41)  评论(0编辑  收藏  举报