Maximum Depth of Binary Tree

来源:互联网 发布:知乎 印度军工 编辑:程序博客网 时间:2024/06/05 22:31

题目104:Maximum Depth of Binary Tree

题目描述:
Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
思路分析:
和求二叉树的最小深度类似的解法类似,有递归和非递归两种解法。

1. 递归解法

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

2. 非递归解法

思路分析:
二叉树的层次遍历,一直遍历到最后一个结点,此时的深度就是求的深度。

class Solution {public:    int maxDepth(TreeNode* root) {        if (0 == root)            return 0;        queue<TreeNode *> que;        int depth, i, len;        que.push(root);        depth = 1;        while (!que.empty()) {            len = que.size();            for (i = 0; i < len; i ++) {                TreeNode *qtop = que.front();                que.pop();                if (qtop->left)                    que.push(qtop->left);                if (qtop->right)                    que.push(qtop->right);            }            if (que.empty())                return depth;            ++ depth;        }    }};

while里面有for循环,还要优化的地方。
用cuc_num统计当前层的结点个数,next_num统计下一层的结点个数。

class Solution {public:    int maxDepth(TreeNode* root) {        if (0 == root)            return 0;        queue<TreeNode *> que;        int cur_num, next_num, depth;        que.push(root);        depth = 1;        cur_num = 1;        next_num = 0;        while (!que.empty()) {            TreeNode *qtop = que.front();            que.pop();            -- cur_num;            if (qtop->left) {                que.push(qtop->left);                ++ next_num;            }            if (qtop->right) {                que.push(qtop->right);                ++ next_num;            }            /* 判断队列是否为空,如果为空,深度不再需要加1 */            if (!que.empty() && 0 == cur_num) {                cur_num = next_num;                next_num = 0;                ++ depth;            }        }        return depth;    }};
0 0