https://github.com/yuanoOo/Algorithm/tree/master/BinaryTree/%E9%81%8D%E5%8E%86%E4%BA%8C%E5%8F%89%E6%A0%91
递归先序遍历
/**
* 递归的方法实现先序遍历二叉树
*/
public static void printBinaryTreeRecursive(Node node){
if (node == null)
return;
System.out.println(node.value + " ");
printBinaryTreeRecursive(node.left);
printBinaryTreeRecursive(node.right);
}
非递归先序遍历
image.png
/**
* 非递归方法实现先序遍历二叉树
*/
public static void printBinaryTree(Node node){
//工程方面不要使用Stack,这是java中过时的api,DeQueue是一个更好的选择
Stack<Node> stack = new Stack<>();// only for convenient
Node current = null;
//1.将头节点head压入stack中
stack.push(node);
while (!stack.isEmpty()){
current = stack.pop();
System.out.print(current.value + " ");
if (current.right != null) stack.push(current.right);
if (current.left != null) stack.push(current.left);
}
}
网友评论