zoukankan      html  css  js  c++  java
  • [Leetcode] Maximum Depth of Binary Tree

    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;
        }
    };
    
    
    

    解题描述

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

  • 相关阅读:
    Spring
    数据库架构
    Spring
    Spring
    Spring
    服务的有状态和无状态(转)
    Java基础
    Ubuntu
    Ubuntu
    Ubuntu
  • 原文地址:https://www.cnblogs.com/yanhewu/p/8359014.html
Copyright © 2011-2022 走看看