【发布时间】:2021-09-20 07:13:50
【问题描述】:
我正在尝试在 Leetcode 上做平衡树问题,只有当左子树的高度 - 右子树的高度 时才返回 true。 为什么左子树的深度应该返回 4 而返回 2?有什么我解释错了吗?我在底部附上了一张树的图片。
输入:[1,2,2,3,3,null,null,4,4,null,null,5,5]
输出:真(因为左子树返回 2 而不是 4)
预期输出:假
打印报表:
左子树:2
右子树:1
结果:1(左子树 - 右子树)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
// 1 2 2 3 3 4 4
//
if (root == null) return true;
System.out.println("left subtree: " + findDepth(root.left,1));
System.out.println("right subtree: " + findDepth(root.right,1));
System.out.println("result: " + Math.abs(findDepth(root.left,1) - findDepth(root.right, 1)));
if ( Math.abs(findDepth(root.left,1) - findDepth(root.right, 1)) <= 1) return true;
return false;
}
public static int findDepth(TreeNode root, int count) {
if (root == null) return count;
if (root.left != null) {
count++;
findDepth(root.left, count);
}
if(root.left == null && root.right == null) return count;
return count;
}
}
【问题讨论】:
-
this 回答你的问题了吗?
-
@Sweeper 基于调试器,计数达到 4 然后开始减少到 2。我不确定为什么在代码中的任何地方没有计数时它会减少。我想了解为什么递归会减少计数器。
标签: java binary-tree