Maximum Depth of Binary Tree ---LeetCode

来源:互联网 发布:python 能做界面吗 编辑:程序博客网 时间:2024/06/07 02:57

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

解题思路:

这道题要找出二叉树的最大深度,显而易见用 DFS 来实现,可以递归实现也可以迭代实现。最大深度即比较左子树与右子树的深度,谁大就输出谁。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int maxDepth(TreeNode root) {        if (root == null) return 0;        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;    }}
0 0
原创粉丝点击