Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.
Example 1:
Given tree [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
return true.
We design a function \(dfs(root)\), which returns the height of the tree with \(root\) as the root node. If the tree with \(root\) as the root node is balanced, it returns the height of the tree, otherwise, it returns \(-1\).
The execution logic of the function \(dfs(root)\) is as follows:
If \(root\) is null, then return \(0\).
Otherwise, we recursively call \(dfs(root.left)\) and \(dfs(root.right)\), and check whether the return values of \(dfs(root.left)\) and \(dfs(root.right)\) are \(-1\). If not, we check whether \(abs(dfs(root.left) - dfs(root.right)) \leq 1\) holds. If it holds, then return \(max(dfs(root.left), dfs(root.right)) + 1\), otherwise return \(-1\).
In the main function, we only need to call \(dfs(root)\), and check whether its return value is \(-1\). If not, return true, otherwise return false.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the number of nodes in the binary tree.
1 2 3 4 5 6 7 8 910111213141516171819
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution:defisBalanced(self,root:TreeNode)->bool:defdfs(root:TreeNode):ifrootisNone:return0l,r=dfs(root.left),dfs(root.right)ifl==-1orr==-1orabs(l-r)>1:return-1returnmax(l,r)+1returndfs(root)>=0
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution{publicbooleanisBalanced(TreeNoderoot){returndfs(root)>=0;}privateintdfs(TreeNoderoot){if(root==null){return0;}intl=dfs(root.left);intr=dfs(root.right);if(l<0||r<0||Math.abs(l-r)>1){return-1;}returnMath.max(l,r)+1;}}
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcisBalanced(root*TreeNode)bool{vardfsfunc(*TreeNode)intdfs=func(root*TreeNode)int{ifroot==nil{return0}l,r:=dfs(root.Left),dfs(root.Right)ifl==-1||r==-1||abs(l-r)>1{return-1}returnmax(l,r)+1}returndfs(root)>=0}funcabs(xint)int{ifx<0{return-x}returnx}