我试图通过将Java代码转换为python,在leetcode上创建一种平衡二叉树的快速解决方案,但是由于某些奇怪的原因,python解决方案抛出了错误的答案。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
result=True
class Solution:
def maxDepth(self,root):
if root==None:
return 0
lh=self.maxDepth(root.left)
rh=self.maxDepth(root.right)
if abs(lh-rh)>1:
result=False
return 0
return max(lh,rh)+1
def isBalanced(self, root: TreeNode) -> bool:
self.maxDepth(root)
return result
链接到问题:https://leetcode.com/problems/balanced-binary-tree/
JAVA代码
public class Solution {
boolean result = true;
public boolean isBalanced(TreeNode root) {
maxDepth(root);
return result;
}
public int maxDepth(TreeNode root){
if(root==null)
return 0;
int l = maxDepth(root.left);
int r = maxDepth(root.right);
if(Math.abs(l-r)>1){
result = false;
return 0; //exit recursion
}
return 1+Math.max(l,r);
}
}