leetcode104

本文介绍了一种计算二叉树最大深度的方法,包括C#和Python两种语言的实现方式。通过递归和非递归两种算法展示了如何遍历二叉树节点并计算其最大深度。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    System.Collections.Generic.Stack<TreeNode> S = new System.Collections.Generic.Stack<TreeNode>();
        int maxDepth = 0;
        void postOrder(TreeNode Node)
        {
            if (Node != null)
            {
                S.Push(Node);
            }
            if (Node != null && Node.left != null)
            {
                postOrder(Node.left);
            }
            if (Node != null && Node.right != null)
            {
                postOrder(Node.right);
            }

            var depth = S.Count;

            maxDepth = Math.Max(depth, maxDepth);
            if (depth > 0)
            {
                S.Pop();
            }
        }
    public int MaxDepth(TreeNode root) {
        postOrder(root);
            Console.WriteLine(maxDepth);
            return maxDepth;
    }
}

https://leetcode.com/problems/maximum-depth-of-binary-tree/#/description

 

补充一个python的实现:

1 class Solution:
2     def maxDepth(self, root: 'TreeNode') -> 'int':
3         if root == None:
4             return 0
5         return max(self.maxDepth(root.left),self.maxDepth(root.right)) + 1
6         

 

转载于:https://www.cnblogs.com/asenyang/p/6732267.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值