树的深度优先遍历,广度优先遍历

package com.lkr.dataStructure;

//import javax.swing.tree.TreeNode;
import java.util.ArrayDeque;
//import com.lkr.dataStructure.TreeNode;

public class TreeBianli {

public static void main(String[] args){
TreeNode root = new TreeNode(1);
TreeNode secondNode = new TreeNode(2);
TreeNode thirdNode = new TreeNode(3);
TreeNode forthNode = new TreeNode(4);
TreeNode fifthNode = new TreeNode(5);
TreeNode sixthNode = new TreeNode(6);
TreeNode seventhNode = new TreeNode(7);
root.right = secondNode;
root.left = thirdNode;
secondNode.right = forthNode;
secondNode.left = fifthNode;
thirdNode.right = sixthNode;
sixthNode.left = seventhNode;

System.out.println("深度优先遍历结果: ");
new TreeBianli().depthOrderTraversal(root);

System.out.println("广度优先遍历结果: ");
new TreeBianli().levelOrderTraversal(root);

}
//深度优先算法采用栈来实现非递归算法
public void depthOrderTraversal(TreeNode root){
if(root==null){
System.out.println("empty tree");
return;
}
ArrayDeque<TreeNode> stack = new ArrayDeque<TreeNode>();
stack.push(root);
while (stack.isEmpty()==false){
TreeNode node = stack.pop();
System.out.print(node.value+" ");
if(node.right != null){
stack.push(node.right);
}
if(node.left != null){
stack.push(node.left);
}
}
System.out.print("\n");
}

//广度优先算法利用队列来实现非递归算法
public void levelOrderTraversal(TreeNode root){
if(null==root){
System.out.println("empth tree");
return;
}
ArrayDeque<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
while(queue.isEmpty()== false){
TreeNode node = queue.remove();
System.out.print(node.value + " ");
if(null != node.left){
queue.add(node.left);
}
if(null != node.right){
queue.add(node.right);
}
}
System.out.print("\n");
}
}
posted @ 2019-02-18 08:17  图图图图胡图图  阅读(759)  评论(0编辑  收藏  举报