Leetcode_maximum-depth-of-binary-tree (updated c++ and python version)

本文介绍了一种求解二叉树最大深度的算法,通过深度优先搜索(DFS)和广度优先搜索(BFS)两种方法实现。讨论了算法的具体实现细节及常见错误,并提供了C++与Python代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

地址:http://oj.leetcode.com/problems/maximum-depth-of-binary-tree/

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.

思路:dfs遍历,记录当前节点的深度并与max_depth比较。

手写WA了几次,第一次没有考虑root为NULL的情况,第二次没有考虑root的左右孩子都是NULL的情况,

第三次因为不清楚Leetcode是一个程序中多次调类方法来测试数据(如果是pat就不用了),所以全局变量没有重置,即maxDepth中max_depth = 0 没写。

此题应该是常考题型。

参考代码:

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

int max_depth = 0;
void dfs(TreeNode* node, int depth)
{
    if(node)
    {
        ++depth;
        if(node->left) 
        {
            dfs(node->left, depth);
        }
        if(node->right)
        {
            dfs(node->right, depth);
        }
    }
    max_depth = max_depth > depth ? max_depth : depth;
}

class Solution {
public:
    int maxDepth(TreeNode *root) {
        max_depth = 0;
        dfs(root, 0);
        return max_depth;
    }
};


 
//SECOND TRIAL, bfs
class Solution {
public :
     int maxDepth ( TreeNode * root ) {
         if ( ! root )
             return 0 ;
         queue < TreeNode *> treeq ;
         treeq . push ( root );
         TreeNode * cur = NULL ;
         int ans = 0 ;
         while ( ! treeq . empty ())
         {
             int sz = treeq . size ();
             ++ ans ;
             while ( sz -- )
             {
                 cur = treeq . front ();
                 treeq . pop ();
                 if ( cur -> left )
                     treeq . push ( cur -> left );
                 if ( cur -> right )
                     treeq . push ( cur -> right );
             }
         }
         return ans ;
     }
};

python:

 
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution :
     # @param root, a tree node
     # @return an integer
     def maxDepth ( self , root ):
         if not root :
             return 0
         q = [ root ]
         ans = 0
         while q :
             sz = len ( q )
             ans += 1
             while sz :
                 sz -= 1
                 cur = q . pop ()
                 if cur . left :
                     q . insert ( 0 , cur . left )
                 if cur . right :
                     q . insert ( 0 , cur . right )
         return ans

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值