LeetCode 104. Maximum Depth of Binary Tree(二叉树高度)

来源:互联网 发布:在淘宝点击卖家没反应 编辑:程序博客网 时间:2024/06/05 10:54

原题网址:https://leetcode.com/problems/maximum-depth-of-binary-tree/

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.

方法:递归+深度优先搜索。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    private int max = 0;    private void check(TreeNode root, int depth) {        if (root == null) return;        if (root.left == null && root.right == null) {            max = Math.max(max, depth);            return;        }        if (root.left != null) check(root.left, depth+1);        if (root.right != null) check(root.right, depth+1);    }    public int maxDepth(TreeNode root) {        max = 0;        check(root, 1);        return max;    }}


0 0
原创粉丝点击