【数据结构】二叉树相关操作
来源:互联网 发布:阿里云域名怎么绑定ip 编辑:程序博客网 时间:2024/05/17 06:03
1、二叉树的层次遍历(leetcode 102)
//二叉树的层次遍历 //利用队列 public void FloorVisit(BinaryTree<T> root) { Queue<BinaryTree> queue = new LinkedList<BinaryTree>(); if(root==null) { return; } BinaryTree<T> current; queue.offer(root); while(!queue.isEmpty()) { current = queue.peek(); queue.poll(); System.out.println(current.value); if (current.left != null) { queue.offer(current.left); } if (current.right != null) { queue.offer(current.right); } } }
2、求二叉树的节点个数
//求二叉树的节点个数 public int numOfNodes(BinaryTree<T> root) { if(root==null) { return 0; } return (numOfNodes(root.left)+numOfNodes(root.right))+1; }
//求二叉树的深度 public int depthOfTree(BinaryTree<T> root) { if(root==null) { return 0; } int left = depthOfTree(root.left); int right = depthOfTree(root.right); return (left>right?left:right)+1; }
//求二叉树的宽度 public int widthOfTree(BinaryTree<T> root) { if(root==null) { return 0; } BinaryTree<T> current = root; Queue<BinaryTree> queue = new LinkedList<BinaryTree>(); queue.offer(root); int width = 0; int tempWidth = queue.size(); while(tempWidth>0) { if(tempWidth>width) { width = tempWidth; } while(tempWidth>0) { current = queue.peek(); queue.poll(); if(current.left!=null) { queue.offer(current.left); } if(current.right!=null) { queue.offer(current.right); } tempWidth--; } tempWidth = queue.size(); } return width; }
5、判断两个树是否相同
//判断两个树是否相同 public boolean isSameTree(BinaryTree<T> root1,BinaryTree<T> root2) { if(root1==null && root2==null) { return true; } if((root1!=null&&root2==null) || (root1==null && root2!=null)) { return false; } if(root1.value!=root2.value) { return false; } return (isSameTree(root1.left,root2.left)&&isSameTree(root1.right,root2.right)); }
//二叉树的镜像转换 public void reverseTree(BinaryTree<T> root) { if(root==null) { return; } BinaryTree<T> temp = null; temp = root.right; root.right = root.left; root.left = temp; //递归调用,把所有的左子树和右子树翻转 reverseTree(root.left); reverseTree(root.right); }
0 0
- 【数据结构】二叉树相关操作
- 数据结构 二叉搜索树的相关操作
- 【数据结构】搜索二叉树的相关操作
- 数据结构:二叉查找树的相关操作
- 数据结构中二叉树的相关操作
- 数据结构--二叉树的创建和相关操作
- 数据结构 实验报告 第四个 二叉树相关操作
- 数据结构与算法简记:二叉查找树相关操作
- 数据结构-二叉树操作
- 二叉树操作--数据结构
- 数据结构二叉树操作
- 数据结构二叉树操作
- 二叉树相关操作
- 二叉树相关操作
- 二叉树相关操作
- 二叉树相关操作
- 二叉树 相关操作
- 二叉树相关操作
- js ES3执行上下文
- 汇编语言第十三章-int中断
- windows 下VS2015配置opencv
- elasticsearch自定义分析器
- 欢迎使用CSDN-markdown编辑器
- 【数据结构】二叉树相关操作
- 项目1-点-圆-圆柱类族的设计(3)
- 1.5linux安装redis
- BZOJ 2342: [Shoi2011]双倍回文 (Manacher+set)
- UFLDL 07 白化 whitening/sphering
- Mac下配置Caffe的Python接口
- elasticsearch中初步使用filter
- 51Nod 1001 数组中和等于K的数对
- 非常详细到docker学习资料