LeetCode:面试题 04.04. 检查平衡性

    技术2024-01-13  98

    深度优先搜索树,得到左子树高度和右子树高度,如果两个高度差超过1,则不是平衡树

    public class MyTest1 { private boolean isBalance = true; public boolean isBalanced(TreeNode root) { dfs(root); return isBalance; } /** * 深度优先,遍历树,返回树的高度 * @param root * @return */ private int dfs(TreeNode root) { if(root==null) { return 0; } int leftDepth = dfs(root.left); int rightDepth = dfs(root.right); if(Math.abs(rightDepth-leftDepth)>1) { isBalance = false; } return Math.max(leftDepth, rightDepth)+1; } }

     

     

     

     

     

     

    Processed: 0.017, SQL: 9