二叉树--判断平衡二叉树
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 }
非递归代码:
也就是对求解树的每个节点的深度进行非递归的操作,不多说了
相关文章推荐
- Win7 系统搭建FTP服务器
- 当textField输入框被键盘遮挡时 让整个view上移
- 对于定义、声明的联系与区别
- jsp el表达式,for循环
- Android架构学习MVC、MVP、MVVM(一)
- 2.AngularJS 作用域( scope )
- Android热修复研究问题汇总
- iOS 9 通讯录崩溃问题
- Navigator对象详解
- Codeforces Round #354 (Div. 2) B. Pyramid of Glasses 模拟
- ubuntu上安装svn客户端
- apache虚拟主机
- java运算符
- delete和delete[]的区别
- 用PHP写的一个冒泡排序法的函数简单实例
- SSH框架总结
- java基础语法(本人学习java的笔记)
- Cell的重用代码
- Android实现记住用户名和密码功能
- 使用golang从雅虎抓取股票交易数据