输入一棵二叉树,判断该二叉树是否是平衡二叉树。
平衡二叉树的概念:为空树,或者左右两边的高度差不超过1
自己想的笨方法:从根部开始,采用前序遍历法,依次求左右子树的深度,然后求它们的差,遇到不符合要求的结点的返回false,否则递归的进行后续子结点的高度的求解
IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
public class Solution { public boolean IsBalanced_Solution(TreeNode root) { if(root == null) return true; while(root != null){ int left = deep(root.left); int right = deep(root.right); if(Math.abs(left - right) > 1) return false; return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right); } return true; } public int deep(TreeNode root){ if(root == null) return 0; return 1 + Math.max(deep(root.left), deep(root.right)); } }
注:上面的方法有个缺点:就是从上往下依次求解的话,会对于每个节点的深度都求解多次,增加不必要的开销。
别人的思路:从下往上的递归求解结点的高度差,若有不符合要求的,则返回false,否则递归向上求解子结点的高度。
而从下往上递归时,是使用后序遍历法来进行求解的
每次都判断左右子树的高度差,若不符合left-right>1的话,则返回-1;
public class Solution { public boolean IsBalanced_Solution(TreeNode root) { if(root == null) return true; return deep(root) != -1; } public int deep(TreeNode root){ if(root == null){ return 0; } int left = deep(root.left); if(left == -1) return -1; int right = deep(root.right); if(right == -1) return -1; return Math.abs(left - right) > 1 ? -1 : Math.max(left, right) + 1; } }