二叉树的先序遍历 递归与非递归实现

先序遍历 :

通俗来讲,就是先打印父节点,然后打印左孩子节点 ,最后打印右孩子节点

举个例子:2 3 分别是 节点1的左右孩子  4 5 分别是节点2 的左右孩子  6 7是节点3的左右孩子

      1

  2       3

 4    5   6   7

先序的遍历的结果为  1  2 4 5 3 6 7

递归代码实现:

public static void preOrderRecur(Node head) {
  if (head == null) {
    return;
  }
  System.out.print(head.value + " ");
  preOrderRecur(head.left);
  preOrderRecur(head.right);
}

 非递归代码实现:

public static void preOrderUnRecur(Node head) {
	System.out.print("pre-order: ");
	if (head != null) {
		Stack<Node> stack = new Stack<Node>();
		stack.add(head);
		while (!stack.isEmpty()) {
			head = stack.pop();
			System.out.print(head.value + " ");
			if (head.right != null) {
				stack.push(head.right);
			}
			if (head.left != null) {
				stack.push(head.left);
			}
		}
	}
	System.out.println();
}

 

posted on 2022-01-12 22:38  机器猫007  阅读(90)  评论(0)    收藏  举报

导航