TreeviewCopyright © aleen42 all right reserved, powered by aleen42

55-I. 二叉树的深度

https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-07-21 21:15:19
 * @Description: https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/
 * @FilePath: \leetcode-googtech\剑指 Offer\#55 - I. 二叉树的深度\Solution.java
 */ 

 /**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

class Solution {
    // 后序遍历(DFS): 递归法
    public int maxDepth(final TreeNode root) {
        if (root == null) {
            return 0;
        }
        // 递归获取左右子树的深度
        final int leftDepth = maxDepth(root.left) + 1;
        final int rightDepth = maxDepth(root.right) + 1;
        // 利获取最大子树深度
        return leftDepth > rightDepth ? leftDepth:rightDepth;
    }
}

Python

'''
@Author: Goog Tech
@Date: 2020-07-21 21:15:26
@Description: https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/
@FilePath: \leetcode-googtech\剑指 Offer\#55 - I. 二叉树的深度\Solution.py
'''
# 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):
    # 后序遍历(DFS): 递归法
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: return 0
        return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""