码迷,mamicode.com
首页 > 其他好文 > 详细

树的深度优先遍历和广度优先遍历非递归实现.

时间:2015-12-17 20:41:52      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

注:树的深度优先遍历就是二叉树的先序遍历.

下面是代码.

 1 package tooffer;
 2 
 3 import java.util.LinkedList;
 4 import java.util.Stack;
 5 
 6 public class TreeNode {
 7     int val = 0;
 8     TreeNode left = null;
 9     TreeNode right = null;
10 
11     public TreeNode(int val) {
12         this.val = val;
13 
14     }
15     
16     
17     /*
18      *树的深度优先遍历 
19      *按树的每一条分支遍历树
20      *利用一个栈进行辅助
21      */
22     public void DeepFirstSearch_NoRecursion(TreeNode root)
23     {
24         Stack<TreeNode> treeStack = new Stack<>();
25         
26         if(root == null)
27         {
28             return;
29         }
30         
31         treeStack.add(root);
32         
33         while(!treeStack.isEmpty())
34         {
35             TreeNode currentNode =  treeStack.pop();//栈顶元素出栈
36             System.out.print(currentNode.val);//访问节点
37             
38             /*深搜需要先访问左子树的一条分支,故右孩子先入栈*/
39             if(currentNode.right != null)
40             {
41                 treeStack.push(currentNode.right);
42             }
43             
44             if(currentNode.left != null)
45             {
46                 treeStack.push(currentNode.left);
47             }
48         }
49     }
50     
51     /*
52      *广度优先遍历 
53      *按照树的每一层进行遍历
54      *利用一个队列进行辅助
55      */
56     public void BreadFirstSearch_NoRecursion(TreeNode root)
57     {
58         LinkedList<TreeNode> treeQueue = new LinkedList<>();//用链表来模拟队列
59         
60         if(root == null)
61         {
62             return;
63         }
64         
65         treeQueue.add(root);
66         
67         while(!treeQueue.isEmpty())
68         {
69             TreeNode currenNode = treeQueue.getFirst(); //获取队首元素
70             
71             System.out.println(currenNode.val);//访问节点
72             
73             if(currenNode.left != null)
74             {
75                 treeQueue.add(currenNode.left);//左子树进队列
76             }
77             
78             if(currenNode.right != null)
79             {
80                 treeQueue.add(currenNode.right);//右子树进队列
81             }
82             
83             treeQueue.removeFirst();//队首元素访问完出队列
84         }
85     }
86 }

 

树的深度优先遍历和广度优先遍历非递归实现.

标签:

原文地址:http://www.cnblogs.com/daimadebanyungong/p/5055097.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!