二叉树的最大高度

/*给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。*/
//递归/*递归

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == NULL)
            return 0;
        int max_left = maxDepth(root->left);
        int max_right = maxDepth(root->right);

        return max_left > max_right ? (max_left+1) : (max_right+1);
    }


};*///采用层次遍历的方法,类似bfs的解法

class Solution {
public:
    int maxDepth(TreeNode* root) {
        int h = 0;
        if (root == NULL)
            return 0;
        queue s;
        s.push(root);

        while (!s.empty())
        {
            int n = s.size();
            while (n--)
            {
                TreeNode* r = s.front();
                s.pop();
                if (r->left != NULL) s.emplace(r->left);
                if (r->right != NULL)s.emplace(r->right);
            }
            h++;
        }
        return h;
    }
};

 

你可能感兴趣的:(leetcode,c++,leetcode)