1. 程式人生 > >非遞迴求二叉樹的深度

非遞迴求二叉樹的深度

可以利用層次遍歷,記錄層數即二叉樹的深度(注意統計每一層結點的個數,以免影響記錄層數)

//藉助層次遍歷,非遞迴
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)); } };