求二叉树的深度和宽度平衡最大距离
来源:互联网 发布:压缩软件 mac 编辑:程序博客网 时间:2024/05/21 09:51
http://www.cnblogs.com/xudong-bupt/p/4036190.html
这个是常见的对二叉树的操作。总结一下:
设节点的数据结构,如下:
1 class TreeNode {2 char val;3 TreeNode left = null;4 TreeNode right = null;5 6 TreeNode(char _val) {7 this.val = _val;8 }9 }
1.二叉树深度
这个可以使用递归,分别求出左子树的深度、右子树的深度,两个深度的较大值+1即可。
1 // 获取最大深度 2 public static int getMaxDepth(TreeNode root) { 3 if (root == null) 4 return 0; 5 else { 6 int left = getMaxDepth(root.left); 7 int right = getMaxDepth(root.right); 8 return 1 + Math.max(left, right); 9 }10 }
2.二叉树宽度
使用队列,层次遍历二叉树。在上一层遍历完成后,下一层的所有节点已经放到队列中,此时队列中的元素个数就是下一层的宽度。以此类推,依次遍历下一层即可求出二叉树的最大宽度。
1 // 获取最大宽度 2 public static int getMaxWidth(TreeNode root) { 3 if (root == null) 4 return 0; 5 6 Queue<TreeNode> queue = new ArrayDeque<TreeNode>(); 7 int maxWitdth = 1; // 最大宽度 8 queue.add(root); // 入队 9 10 while (true) {11 int len = queue.size(); // 当前层的节点个数12 if (len == 0)13 break;14 while (len > 0) {// 如果当前层,还有节点15 TreeNode t = queue.poll();16 len--;17 if (t.left != null)18 queue.add(t.left); // 下一层节点入队19 if (t.right != null)20 queue.add(t.right);// 下一层节点入队21 }22 maxWitdth = Math.max(maxWitdth, queue.size());23 }24 return maxWitdth;25 }
所有节点只遍历一遍的算法
bool IsBalanced(BinaryTreeNode *pRoot, int *pDepth)
{
if (pRoot == NULL)
{
*pDepth = 0;//当前节点高度为0,从叶子节点往上算高度
return true;
}
int left, right;
if (IsBalanced(pRoot->lchild, &left) && IsBalanced(pRoot->rchild, &right))
{
int diff = left - right;
if (diff <= 1 && diff >= -1)
{
*pDepth = 1 + (left > right ? left : right);
return true;
}
}
return false;
}
4
方法一:求二叉树中节点的最大距离,等同于“计算每个节点的左子树和右子树的高度和,取最大值”
- int height(BiTree T, int &max)
- {
- if(!T)
- return -1;
- int i=height(T->lchild,max)+1;
- int j=height(T->rchild,max)+1;
- int distance=i+j;
- if(max<distance) max=distance;
- return i>j?i:j;
- }
- int maxdistance(BiTree T)
- {
- int maxdis=0;
- height(T, maxdis);
- return maxdis;
- }
方法二:见编程之美(动态规划),修改3的方法,从叶子节点开始累加高度
所有节点只遍历一遍的算法
void getDepth(BinaryTreeNode *pRoot, int *pDepth)
{
if (pRoot == NULL)
{
*pDepth = 0;//当前节点高度为0,从叶子节点往上算高度
return true;
}
int left, right;
getDepth(pRoot->lchild, &left);
getDepth(pRoot->rchild, &right);
gMaxLen = gMaxLen > (left + right) ? (gMaxLen : (left + right));
*pDepth = 1 + (left > right ? left : right);
}
- 求二叉树的深度和宽度平衡最大距离
- 求二叉树的宽度(结点的最大距离)
- 求二叉树的最大深度与最大宽度
- 二叉树的最大深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 找出二叉树的最大宽度和最大深度
- 二叉树的最大深度和最大宽度
- 求树的最大宽度和最大深度
- 求二叉数的深度和宽度
- 求二叉数的深度和宽度
- 求二叉树宽度和深度
- FZU1404 Andy的作业
- POJ 3349
- HUST 1408
- IOS支付宝集成一系列问题
- chmod命令详解
- 求二叉树的深度和宽度平衡最大距离
- PAT-PAT (Advanced Level) Practise 1001. A+B Format (20) 【二星级】
- scala学习第四章 映射和元组
- 15.8.19笔记
- Oracle ORA-01940 无法删除当前已连接用户
- TCP/IP协议三次握手与四次握手流程解析
- 2015-8-19省赛模拟总结
- PHP 的var const static define self $this 使用详解
- iostat和iowait详细解说(转载:http://oplinux.com/order/iostat.html)