码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Maximum Depth of Binary Tree

时间:2018-01-26 14:02:47      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:node   nod   its   maximum   https   htm   log   markdown   max   

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

标签:node   nod   its   maximum   https   htm   log   markdown   max   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!