leetcode104

时间:2024-04-28 00:05:23
/**
* 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 = ;
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 > )
{
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的实现:

 class Solution:
def maxDepth(self, root: 'TreeNode') -> 'int':
if root == None:
return
return max(self.maxDepth(root.left),self.maxDepth(root.right)) +