首页 > 其他 > 详细

[Leetcode] Maximum Depth of Binary Tree

时间:2018-01-26 13:19:13      阅读:187      评论:0      收藏:0      [点我收藏+]

Maximum Depth of Binary Tree 题解

原创文章,拒绝转载

题目来源:https://leetcode.com/problems/maximum-depth-of-binary-tree/description/


Description

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.

Solution


class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == NULL) return 0;
        int res = 0;
        queue<TreeNode*> q;
        q.push(root);
        q.push(NULL);
        while (!q.empty()) {
            TreeNode* node = q.front();
            q.pop();
            if (node != NULL) {
                if (node -> left != NULL)
                    q.push(node -> left);
                if (node -> right != NULL)
                    q.push(node -> right);
            } else {
                res++;
                if (!q.empty())
                    q.push(NULL);
            }
        }
        return res;
    }
};

解题描述

这道题题意是求二叉树的深度,上面的解法用到的是迭代法层次遍历来计算二叉树深度,使用的方法和层次遍历相近。

[Leetcode] Maximum Depth of Binary Tree

原文:https://www.cnblogs.com/yanhewu/p/8359014.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!