平衡二叉树的判定
来源:互联网 发布:软件测试工程师的出路 编辑:程序博客网 时间:2024/06/05 10:49
平衡二叉树的一个重要性质:左子树和右子树的树高的差的绝对值小于等于1。
Java实现:
public int treeDepth(TreeNode node) { if (node == null) { return 0; } int leftDepth = treeDepth(node.left); int rightDepth = treeDepth(node.right); return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1); } public boolean IsBalanced_Solution(TreeNode node) { if(node==null){ return true; } if(Math.abs(treeDepth(node.left)-treeDepth(node.right))>1){ return false; } return IsBalanced_Solution(node.left)&&IsBalanced_Solution(node.right); }
阅读全文