LeetCode: 104. Maximum Depth of Binary Tree-简单-Python+Java

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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
 
解题思路:
Recursion是最直接的方式:
如果这个node是null,那么就直接return 0
如果不是null,recursion 它的left node 和right node, 取两个值中的max值+1 就是最大深度
也可以用Iterative去解,一层一层去遍历元素,每遍历一层,高度加一,直到该层的元素为空
 
Java:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null) return 0;
        return Math.max(maxDepth(root.left), maxDepth(root.right))+1;
    }
}

Python:

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

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        else:
            return max(self.maxDepth(root.left),self.maxDepth(root.right))+1
Iterative方式
class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        height = 0
        if root==None:
            return height;
        level = [root]
        while level:
            temp = []
            for val in level:
                if val.right:
                    temp.append(val.right)
                if val.left:
                    temp.append(val.left)
            level = temp
            height += 1
        return height

 

 
 

posted on 2019-09-16 11:19  cherryjing0629  阅读(114)  评论(0编辑  收藏  举报

导航