Leetcode_num2_Maximum Depth of Binary Tree

本文介绍了一种使用递归方法求解二叉树最大深度的问题,并通过Python及C++实现了解决方案,强调了避免重复递归调用的重要性。

题目:

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.


AC率第二高的题啦。二项树的最长路径。初看此题就感觉要用递归,但不知怎的。一開始想到深度遍历上去了。。。。囧

实际上非常easy的,某一节点的最长路径=max(该节点左子树的最长路径,该节点右子树的最长路径)+1

另一点就是类中函数调用函数时格式为 self.函数名,否则会报 global name XXX is not defined

废话不多说啦,上代码咯

# 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 root==None:
            return 0
        else:
            p=max(self.maxDepth(root.left),self.maxDepth(root.right))+1
            return p

补充更新ing~~~~

今天刷笔试题的时候又遇到了这道题,可是仅仅能用c++来写,于是高速地写出了例如以下代码:

class Solution {
public:
    int maxDepth(TreeNode *root) {
      if (root==NULL)
          return 0;
      else{
      	int rs=0;
        if(maxDepth(root->left)>maxDepth(root->right)){
        	rs=1+maxDepth(root->left);
        }
        else{
        	rs=1+maxDepth(root->right);
        }
        return rs;
      }
    }
};

一执行,结果TLE了。

。。。。

细致检查发现该程序在推断和计算的过程中反复调用了递归函数,添加了算法复杂度,因此会出现TLE

改动后的代码例如以下:

class Solution {
public:
    int maxDepth(TreeNode *root) {
      if (root==NULL)
          return 0;
      else{
      	int rs=0;
        int left=maxDepth(root->left);
        int right=maxDepth(root->right);
        if(left>right){
        	rs=1+left;
        }
        else{
        	rs=1+right;
        }
        return rs;
      }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值