/**
 * 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         

 

Java的实现:

 1 class Solution {
 2     public int maxDepth(TreeNode root) {
 3         if(root == null){
 4             return 0;
 5         }
 6         int left = maxDepth(root.left);
 7         int right = maxDepth(root.right);
 8         return Math.max(left,right) + 1;
 9     }
10 }

 

posted on 2017-04-19 10:59  Sempron2800+  阅读(123)  评论(0编辑  收藏  举报