非递归求二叉树的深度

来源:互联网 发布:身份证录入软件 编辑:程序博客网 时间:2024/05/16 05:02

可以利用层次遍历,记录层数即二叉树的深度(注意统计每一层结点的个数,以免影响记录层数)

//借助层次遍历,非递归class Solution {public:    int TreeDepth(TreeNode* pRoot)    {        queue<TreeNode*> q;        if (!pRoot) return 0;        q.push(pRoot);        int level = 0;        while (!q.empty()) {            int len = q.size();            level++;            while (len--) {                TreeNode* tem = q.front();                q.pop();                if (tem->left) q.push(tem->left);                if (tem->right) q.push(tem->right);            }        }        return level;    }};//递归class Solution {public:    int TreeDepth(TreeNode* pRoot)    {        if (pRoot == NULL)            return 0;        else            return max(1 + TreeDepth(pRoot->left), 1 + TreeDepth(pRoot->right));    }};
阅读全文
0 0
原创粉丝点击