LeetCode-Balanced Binary Tree && 二叉树的深度 && 二叉树的平衡
来源:互联网 发布:reactrouter 源码详解 编辑:程序博客网 时间:2024/06/17 00:33
作者:disappearedgod
文章出处:http://blog.csdn.net/disappearedgod/article/details/26359533
时间:2014-5-20
题目
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
《剑指offer-面试题39》P207
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点一次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
二叉树定义如下:
struct BinaryTreeNode{ int m_nValue; BinaryTreeNode* m_pLeft; BinaryTreeNode* m_pRight;}
题目二:输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
解法
迭代
第一种想法有点像所见即所得。
无非就先算层次深度,然后计算一下左右子树的差别,然后判断输出真假。
就像我们本科时候学过的:
如果左右子树的深度差大于等于2的话,返回不平衡。(1计算深度,2比较,3子树要迭代)
public boolean isBalanced(TreeNode root) { if(root==null ) return true; int diff = Depth(root.left)-Depth(root.right); if(diff > 1 || diff < -1) return false; return isBalanced(root.left) && isBalanced(root.right); } public int Depth(TreeNode root){ if(root == null) return 0; int left = Depth(root.left); int right = Depth(root.right); return left>right ? left+1 : right + 1; }
另一种想法
public static int depth=0; public static int left=0,right=0; public static int diff = 0; public boolean isBalanced(TreeNode root) { if(root == null){ depth = 0; return true; } if(isBalanced(root.left,left)&&isBalanced(root.right,right)){ diff = left - right; if(diff<=1 && diff > -1){ depth = left > right ? left +1 : right + 1; return true; } } return false; }
返回
LeetCode Solution(持续更新,java>c++)
0 0
- LeetCode-Balanced Binary Tree && 二叉树的深度 && 二叉树的平衡
- LeetCode:Balanced Binary Tree(平衡二叉树的判断)
- leetcode 110. Balanced Binary Tree-平衡二叉树|深度遍历
- leetcode 110. Balanced Binary Tree(平衡二叉树的判断) DFS深度优先遍历
- 【LeetCode】Balanced Binary Tree,平衡二叉树
- [LeetCode] Balanced Binary Tree 平衡二叉树
- Leetcode Balanced Binary Tree 平衡二叉树
- 二叉树的深度&判断一棵二叉树是否是平衡二叉树&110. Balanced Binary Tree
- Balanced Binary Tree 平衡二叉树的检验
- Balanced Binary Tree 平衡二叉树的判断
- LeetCode OJ 之 Balanced Binary Tree (平衡二叉树的判断)
- Balanced Binary Tree 判断是否平衡二叉树 @LeetCode
- LeetCode | Balanced Binary Tree(平衡二叉树)
- leetcode Balanced Binary Tree 平衡二叉树判定
- LeetCode 110 Balanced Binary Tree(平衡二叉树)(*)
- LeetCode 110. Balanced Binary Tree(平衡二叉树)
- Leetcode 110. Balanced Binary Tree 平衡二叉树 解题报告
- leetcode -- 110. Balanced Binary Tree 【二叉树是否平衡】
- 浅议 Dynamic_cast 和 RTTI
- ibatis 中 $与#的区别
- android学习——控制硬加速 hardwareAccelerated 在3.0才有的。
- cocos2d-x入门学习(五)跨版本代码移植实例之【梦幻连连看】
- 嗡ong 咕gū噜lū 咕gū列liè 啥lìn 梭suō哈hā
- LeetCode-Balanced Binary Tree && 二叉树的深度 && 二叉树的平衡
- bower解决js的依赖管理备记
- mysql navicat导出表的三种方法
- [综合面试] 2014校招暑假实习生面经(阿里、百度offer)
- Tomcat Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
- poj3352
- 用meta-data配置参数
- (四)脚本上下文
- MacOS安装mod_python