樹的深度優先遍歷,廣度優先遍歷
阿新 • • 發佈:2019-02-18
cond args pac main ray seve nth package 深度優先算法
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");
}
}
樹的深度優先遍歷,廣度優先遍歷