判断一棵树是不是二叉平衡树

末蓝、 2023-07-24 11:56 141阅读 0赞

转载代码:

  1. public class Solution {
  2. private boolean isBalanced = false;//最后的返回值
  3. public boolean IsBalanced_Solution(TreeNode root) {
  4. getDepth(root);
  5. return isBalanced;
  6. }
  7. public int getDepth(TreeNode root) {
  8. if(root == null) {
  9. isBalanced = true;
  10. return 0;
  11. }
  12. int left = getDepth(root.left);//递归左子树
  13. int right = getDepth(root.right);//递归右子树
  14. int depth = (left > right ? left : right) + 1;
  15. if(Math.abs(left - right) <= 1) {
  16. isBalanced = true;
  17. } else {
  18. isBalanced = false;
  19. }
  20. return depth;
  21. }
  22. }

转载地址:https://blog.csdn.net/endif6/article/details/82356256

发表评论

表情:
评论列表 (有 0 条评论,141人围观)

还没有评论,来说两句吧...

相关阅读