首页 > 试题广场 >

判断是不是平衡二叉树

[编程题]判断是不是平衡二叉树
  • 热度指数:532799 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
输入一棵节点数为 n 二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
样例解释:
样例二叉树如图,为一颗平衡二叉树
注:我们约定空树是平衡二叉树。

数据范围:,树上节点的val值满足
要求:空间复杂度,时间复杂度

输入描述:
输入一棵二叉树的根节点


输出描述:
输出一个布尔类型的值
示例1

输入

{1,2,3,4,5,6,7}

输出

true
示例2

输入

{}

输出

true

说明:本题目包含复杂数据结构TreeNode,点此查看相关信息
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return bool布尔型
     */
    public boolean IsBalanced_Solution (TreeNode pRoot) {
        returnType res = judge(pRoot);
        return res.isBS;
    }

    public returnType judge(TreeNode pRoot){
        //向左右子树索要信息:1. 左右子树的高度;2. 左右子树是否平衡
        returnType res = new returnType(0, false);
        if(pRoot == null){
            res.isBS = true;
            return res;
        }
        returnType l_res =  judge(pRoot.left);
        returnType r_res =  judge(pRoot.right);
        res.depth = Math.max(l_res.depth, r_res.depth) + 1;
        if(!l_res.isBS || !r_res.isBS) return res;
        if(Math.abs(l_res.depth - r_res.depth) > 1) return res;
        res.isBS = true;
        return res;
    }

    public class returnType {
        int depth = 0;
        boolean isBS = false;
        public returnType(int depth, boolean isBS){
            this.depth = depth;
            this.isBS = isBS;
        }
    } 
}

编辑于 2024-04-11 18:05:20 回复(0)
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pRoot TreeNode类
     * @return bool布尔型
     */
    public boolean IsBalanced_Solution (TreeNode pRoot) {
        // write code here
        if (pRoot == null) {
            return true;
        } else  {
            if (Math.abs(maxDeep(pRoot.left) - maxDeep(pRoot.right)) <=1) {
                return true;
            } else return false;
        }
    }

    public int maxDeep(TreeNode root) {
        if (root != null ) {
            return 1 + Math.max(maxDeep(root.left), maxDeep(root.right));
        } else {
            return 0;
        }
    }
}

发表于 2024-03-28 10:51:28 回复(1)
public class Solution {
    /**
     * 输入一棵节点数为 n 二叉树,判断该二叉树是否是平衡二叉树。
     *
     *
     * @param pRoot TreeNode类
     * @return bool布尔型
     */
    public boolean IsBalanced_Solution (TreeNode pRoot) {
        if (null == pRoot) {
            return true;
        }
        if (Math.abs(getHeight(pRoot.left) - getHeight(pRoot.right)) > 1) {
            return false;
        }
        return IsBalanced_Solution(pRoot.left) && IsBalanced_Solution(pRoot.right);
    }

    public int getHeight(TreeNode pRoot) {
        if (null == pRoot) {
            return 0;
        }
        return 1 + Math.max(getHeight(pRoot.left), getHeight(pRoot.right));
    }

}

发表于 2023-10-18 18:27:15 回复(0)
import java.util.*;

public class Solution {
    public boolean IsBalanced_Solution (TreeNode pRoot) {
        return heightT(pRoot) != -2;
    }

    public int heightT (TreeNode root) {
        if (root == null) {
            return 0;
        }
        int l = heightT(root.left);
        int r = heightT(root.right);
        if (Math.abs(l - r) > 1) {
            l = -2;
        }
        return l == -2 ? -2 : Math.max(l, r) + 1;
    }
}
发表于 2023-08-15 14:06:09 回复(1)
dfs、后序遍历
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return bool布尔型
     */
    public static boolean flag = true;
    public boolean IsBalanced_Solution (TreeNode pRoot) {
        // write code here
        // dfs、递归后序遍历
        dfs(pRoot);
        return flag;
    }

    public static int dfs(TreeNode p) {
        // 递归终止条件
        if (p == null || flag == false) return 0; // 优化
        int leftHeight = dfs(p.left);
        int rightHeight = dfs(p.right);
        // 本层递归逻辑
        if ((leftHeight - rightHeight) > 1 || (rightHeight - leftHeight) > 1) {
            flag = false;
            return 0;
        }
        return leftHeight > rightHeight ? (leftHeight + 1) : (rightHeight + 1);
    }
}


发表于 2023-07-18 10:35:10 回复(0)
public boolean IsBalanced_Solution (TreeNode pRoot) {
        if(pRoot==null) return true;
        int ans=build(pRoot);
        if(ans>=1) return true;
        else return false;
    }
    public int build(TreeNode pRoot){  //返回树的高度
        if(pRoot==null){
            return 1;
        }
        int leftH=build(pRoot.left);
        int rightH=build(pRoot.right);
        if(Math.abs(leftH-rightH)>1){
            return -1;
        }
        return Math.max(leftH,rightH)+1;
    }

发表于 2023-07-12 16:36:03 回复(0)
public class Solution {
    boolean res = true;
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null ) return true;
        panduan(root);
        return res;
    }

    public int panduan(TreeNode root){
        if(root == null) return 0;
        int left = 1+panduan(root.left);
        int right = 1+panduan(root.right);
        if(Math.abs(left - right) > 1){
            res=false;
        }
        return Math.max(left,right);
    }
}

发表于 2023-06-11 10:52:26 回复(0)
非递归, 时间复杂度O(N), 空间复杂度O(N), 空间复杂度 O1 就太难了, 至少困难++级别。
import java.util.*;
public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if (root == null) return true;
        Stack<TreeNode> stack = new Stack<>();
        HashMap<TreeNode, Integer> nodeDepthMap = new HashMap<>();
        nodeDepthMap.put(null, 0);
        stack.push(root);
        while (! stack.isEmpty()) {
            root = stack.pop();
            if (root == null) {
                root = stack.pop();
                int leftDepth = nodeDepthMap.get(root.left);
                int rightDepth = nodeDepthMap.get(root.right);
                if (Math.abs(leftDepth - rightDepth) > 1) {
                    return false;
                }
                nodeDepthMap.put(root, 1 + Math.max(leftDepth, rightDepth));
            } else {
                stack.push(root);
                stack.push(null);
                if (root.right != null) stack.push(root.right);
                if (root.left != null) stack.push(root.left);
            }
        }
        return true;
    }
}


发表于 2022-12-20 07:02:13 回复(0)
public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (Math.abs(getMaxDepth(root.left) - getMaxDepth(root.right)) > 1) {
            return false;
        }
        return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);

    }

    private int getMaxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Integer.max(getMaxDepth(root.left), getMaxDepth(root.right)) + 1;
    }
}

发表于 2022-11-12 15:21:59 回复(0)
递归一个函数,计算左右树的层,只要不等于-1,那就符合平衡树
public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null)
            return true;
        return (dfs_tree(root) != -1);
    }
    public int dfs_tree(TreeNode root) {
        // null 返回0,表示当前root只有0层
        if(root == null){
            return 0;
        }
        // 左递归拿到左子树层
        int l = dfs_tree(root.left);
        // 右递归拿到右子树层
        int r = dfs_tree(root.right);
        // 如果左子树 或 右子树 其中一个小于0, 或者l-r的绝对值超过了1,那么返回-1 表示不是平衡树
        if((l < 0 || r < 0 ) || (Math.abs(l-r) > 1)) return -1;
        
        // 返回 左右子树层数取最大值, + 当前层1
        return Math.max(l,r)+1;
    }
}


发表于 2022-11-07 13:18:30 回复(0)
题目要求空间复杂读O(1)没人看到?
发表于 2022-10-23 19:21:16 回复(0)
public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        boolean flag;
        if (root == null) return true;
        if (Math.abs(Maxdepth(root.left) - Maxdepth(root.right)) <= 1) {
            flag = true;
        } else {flag = false;}
        flag = flag && IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
        return flag;
    }

    int Maxdepth(TreeNode root) {
        if (root == null) return 0;
        return Math.max(Maxdepth(root.left), Maxdepth(root.right)) + 1;
    }
}

发表于 2022-10-12 18:54:45 回复(0)
public class Solution {
    boolean tag = true;
    public boolean IsBalanced_Solution(TreeNode root) {
        height(root);
        return tag;
    }

    private int height(TreeNode t) {
        if (t == null) return 0;

        int left = height(t.left);
        int right = height(t.right);

        if (Math.abs(left - right) > 1) tag = false;

        return left > right ? left + 1 : right + 1;
    }
}

发表于 2022-09-04 21:48:44 回复(0)
为什么题目要求O(1)的空间,而包括官方在内的所有的题解都是O(n)的解决方案呢?
发表于 2022-08-19 16:45:21 回复(0)
import java.util.*;
public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        //maybe递归---//是左右的高度差即深度差不大于1
        if(root==null){return true;}
        ArrayList<ArrayList<Integer>> list1=new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> sublist1=new ArrayList<Integer>();
        ArrayList<ArrayList<Integer>> list2=new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> sublist2=new ArrayList<Integer>();
        int level_left=level(root.left,list1,sublist1);
        int level_right=level(root.right,list2,sublist2);
        if(Math.abs(level_left-level_right)>1){return false;}
        return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
    
       
    }
    public int level(TreeNode root,ArrayList<ArrayList<Integer>> list,ArrayList<Integer> sublist){
        //用层序遍历来找深度try
        if(root==null){return 0;}
        Deque<TreeNode> deque=new LinkedList<TreeNode>();
        deque.addLast(root);
        int level=0;
        while(!deque.isEmpty()){
            for(int i=0;i<deque.size();i++){
                 TreeNode cur=deque.removeFirst();
                 sublist.add(cur.val);
                 if(cur.left!=null){deque.addLast(cur.left);}
                 if(cur.right!=null){deque.addLast(cur.right);}
            }
            list.add(new ArrayList(sublist));
            level=level+1;    
        }
        return level;    
    }
}

发表于 2022-07-25 15:58:31 回复(0)
思路:按照平衡二叉树 递归定义:
  1. 左子树 和 右子树的深度不能超过 1;
  2. 左子树 和 右子树 也是平衡二叉树;
public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if (root == null) {
            return true;
        }
        // 按照平衡二叉树 递归定义:
        // 1. 左子树 和 右子树的深度不能超过 1;
        // 2. 左子树 和 右子树 也是平衡二叉树;
        return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 && IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
    }
    
    private int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}


发表于 2022-07-23 18:50:28 回复(0)
public class Solution {
    private boolean isBalanced = true;
    public boolean IsBalanced_Solution(TreeNode root) {
        getDepth(root);
        return isBalanced;
    }
    private int getDepth(TreeNode root){
        if(root == null) return 0;
        int left = getDepth(root.left);
        int right = getDepth(root.right);
        
        if(Math.abs(left-right) > 1){
            isBalanced = false;
        }
        return Math.max(left,right)+1;
     }
}


发表于 2022-07-11 22:39:55 回复(0)

问题信息

难度:
206条回答 112187浏览

热门推荐

通过挑战的用户

查看代码