本文參考自《劍指offer》一書,代碼采用Java語言。
題目
輸入一棵二叉樹的根結點,判斷該樹是不是平衡二叉樹。如果某二叉樹中任意結點的左右子樹的深度相差不超過1,那么它就是一棵平衡二叉樹。
思路
在(55-1) 二叉樹的深度基礎上修改:計算樹的深度,樹的深度=max(左子樹深度,右子樹深度)+1。在遍歷過程中,判斷左右子樹深度相差是否超過1,如果不平衡,則令樹的深度=-1,用來表示樹不平衡。最終根據樹的深度是否等於-1來確定是否為平衡樹。
測試算例
1.功能測試(左斜樹、右斜樹、平衡或者不平衡樹)
3.特殊測試(一個結點,null)
Java代碼
//題目:輸入一棵二叉樹的根結點,判斷該樹是不是平衡二叉樹。如果某二叉樹中 //任意結點的左右子樹的深度相差不超過1,那么它就是一棵平衡二叉樹。 public class BalancedBinaryTree { public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public boolean IsBalanced_Solution(TreeNode root) { return getDepth(root)!=-1; } public int getDepth(TreeNode root) { if(root==null) return 0; int left=getDepth(root.left); if(left==-1) return -1; int right=getDepth(root.right); if(right==-1) return -1; return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(left, right); } /* //自己開始想的方法,但是一定要把樹給遍歷完才行;上面的方法實現了剪枝 boolean isBalanced=true; public boolean IsBalanced_Solution(TreeNode root) { TreeDepth(root); return isBalanced; } public int TreeDepth(TreeNode root) { if(root==null) return 0; int left=TreeDepth(root.left); int right=TreeDepth(root.right); if(left-right>1 || right-left>1) isBalanced=false; return Math.max(left+1,right+1); } */ }
收獲
1.在判斷出樹不平衡后,進行剪枝(即代碼中直接返回-1,不再對其他子樹進行判斷),以提高效率。