中级农民
- 积分
- 106
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-11-29
- 最后登录
- 1970-1-1
|
- public static int longestLength(TreeNode root) {
- if (root == null)
- return 0;
- ArrayList<Integer> max = new ArrayList<Integer>();
- max.add(0);
- TreeNode cur = root;
- TreeNode pre = null;
- helper(cur, pre, max);
- return max.get(0);
- }
- private static int helper(TreeNode cur, TreeNode pre, ArrayList<Integer> max) {
- if (cur == null) {
- return 0;
- }
- //get the left depth starting from cur node
- int left = helper(cur.left, cur, max) + 1;
- //get the right depth starting from cur node
- int right = helper(cur.right, cur, max) + 1;
- //get the local max between left depth and right depth
- int localMax = Math.max(left, right);
- //compare total max with local max
- if (max.get(0) < localMax)
- max.set(0, localMax);
- //return value
- //according to the directions
- if (pre != null) {
- if (pre.left == cur)
- return left;
- else
- return right;
- //root node, return local max as the max depth
- } else
- return localMax;
- }
复制代码 |
|