二叉树递归求高度,非递归求高度,层次遍历
来源:互联网 发布:科比的技术特点知乎 编辑:程序博客网 时间:2024/05/17 22:57
import java.util.LinkedList;import java.util.Queue;public class Main { //非递归求高度 public static int bTNonRecursiveHeight(Node root){ int front=-1,rear=-1; int level=0,last=0; Node[] queue=new Node[1000]; if(root==null) return 0; queue[++rear]=root; while(front<rear){ Node p=queue[++front]; if(p.left!=null){ queue[++rear]=p.left; } if(p.right!=null){ queue[++rear]=p.right; } if(front==last){ level++; last=rear; } } return level; } //递归求高度 public static int bTRecursiveHeight(Node node){ if(node==null) return 0; int leftdepth=bTRecursiveHeight(node.left); int rightdepth=bTRecursiveHeight(node.right); return leftdepth>rightdepth?leftdepth+1:rightdepth+1; } //层次遍历 public static void levelTraversal(Node root){ if(root==null) return; Queue<Node> queue=new LinkedList<Node>(); queue.add(root); int level=0; int count=1; while(!queue.isEmpty()){ Node n=queue.poll(); System.out.print(n.data+" "); if(count==Math.pow(2,level)){ level++; count=0; System.out.println(); } if(n.left!=null){ queue.add(n.left); } if(n.right!=null){ queue.add(n.right); } count++; } } public static void main(String[] args) { Node root=new Node(10); Node a=new Node(4); Node b=new Node(20); Node c=new Node(3); Node d=new Node(5); Node e=new Node(15); Node f=new Node(25); root.left=a; root.right=b; a.left=c; a.right=d; b.left=e; b.right=f; System.out.println(bTNonRecursiveHeight(root)); System.out.println(bTRecursiveHeight(root)); levelTraversal(root); }}class Node{ int data; Node left; Node right; public Node(int data){ this.data=data; }}
阅读全文
0 0
- 利用层次遍历非递归求二叉树高度
- 层次遍历求二叉树的高度(非递归)
- 二叉树递归求高度,非递归求高度,层次遍历
- 求二叉树的高度(非递归)
- 二叉树非递归遍历、层次遍历、高度、节点数
- 二叉树基本算法,递归非递归遍历以及求高度、宽度等
- 二叉树各种遍历的实现(递归、非递归、层次、高度和节点数目)
- 非递归求树的高度
- 求树高度的非递归算法
- 递归求二叉树的高度
- 递归求二叉树的高度
- 4-8 求二叉树高度 *(递归)
- 二叉树(递归遍历和非递归遍历)(递归求树的高度以及叶子节点数和拷贝树)
- java语言实现的二叉树的各种操作(包括递归与非递归遍历二叉树,求二叉树的高度,节点总数,叶子节点等)
- 二叉树的操作3非递归算法求二叉树的高度
- 二叉树遍历(层次,递归,非递归)
- 二叉树的遍历,递归和非递归,求深度
- 树的操作(构造,遍历,求高度,查找)非递归
- HDU1001
- android-Ultra-Pull-To-Refresh/内含滑动冲突解决
- strcmp,strncmp ,memcmp函数
- Test4(2)求一个n阶方阵对角线元素之和
- Unit Testing with Sinon.JS
- 二叉树递归求高度,非递归求高度,层次遍历
- C++之命名空间
- 删除一个文件夹
- AI与游戏——吃豆人(3)基本路径规划算法(下)
- HDU1004
- 星际穿越
- 2017-9-16
- poj1679 The Unique MST 次小生成树
- mysql_高级查询