您的位置:首页 > 其它

二叉树--判断平衡二叉树

2016-05-26 15:37 253 查看
判断一棵树是不是平衡二叉树,平衡二叉树的定义就是,左右子树的差的绝对值不超过1,其实也就是求解出每个节点的左右子树的深度差。

代码如下:

public boolean isBalanced(TreeNode root) {
if (root == null) return true;
if(!isBalanced(root.left)) return false;
if (!isBalanced(root.right)) return false;
return Math.abs(depth(root.left) - depth(root.right)) <=1;

}

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


public boolean isBalanced(TreeNode root) {
return checkBalance(root) == -1 ? false : true;
}

// 1. If a subtree is hit as unbalanced, the whole tree is unbalanced. In this case, -1 is set as the return value.
// 2. If the left subtree and the right subtree of a node are balanced, there are two more cases:
// 2.1. The tree rooted at the node is unbalanced (the depth of its two subtrees differs by more than 1), as a result, -1 is returned.
// 2.2 The tree rooted at the node is balanced, then the depth of the tree will be returned.
public int checkBalance(TreeNode node){
if (node == null) // case 2.2
return 0;

int left = checkBalance(node.left);
if (left == -1) // check case 1
return -1;

int right = checkBalance(node.right);
if (right == -1) // check case 1
return -1;

if (left - right > 1 || right - left > 1)
return -1; // check case 2.1

return (left > right ? left : right) + 1; // case 2.2
}


非递归代码:

也就是对求解树的每个节点的深度进行非递归的操作,不多说了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: