LeetCode.104. Maximum Depth of Binary Tree

来源:互联网 发布:程序员上班都干什么 编辑:程序博客网 时间:2024/06/05 16:10

数据结构没学好,对这个题没有思路,简单看了下二叉树的基本概念。找了一份正确答案研究。

public class Solution {    public int maxDepth(TreeNode root) { if (root == null){            return 0;        }        List <Integer> res = new ArrayList<>();        dfs(res, root, 0);        return res.get(0);    }    private void dfs(List<Integer> res, TreeNode curr, int count) {        count += 1;        if(curr.left == null && curr.right == null){            if (res.isEmpty()){                res.add(count);            }            if (count > res.get(0)){                res.set(0, count);                return;            };        }        if (curr.left != null) {            dfs(res, curr.left, count);        };        if (curr.right != null) {            dfs(res, curr.right, count);        };     }}

必须用递归?
为什么定义了一个没有返回值的方法?
为什么不直接用整形变量存放当前最大的深度而用List?

0 0
原创粉丝点击