前序遍历二叉树(非递归)

来源:互联网 发布:摩根华鑫基金 知乎 编辑:程序博客网 时间:2024/05/21 17:00

前一篇做了leetcode一道二叉树的hard模式,感觉自己对二叉树的一些数据结构不太敏感,于是打算做个总结,把二叉树的常见遍历方式记录一下,从本篇开始,将按如下顺序实现:

1.前序遍历二叉树(非递归)

2.中序遍历二叉树(非递归)

3.后续遍历二叉树(非递归)

4.前序遍历二叉树(递归)

5.中序遍历二叉树(递归)

6.后续遍历二叉树(递归)


本篇为1.前序遍历二叉树,上代码:

package javatest;import java.util.Arrays;import java.util.List;//Java program to implement iterative preorder traversalimport java.util.Stack;//A binary tree nodeclass Node {int data;Node left, right;Node(int item) {data = item;left = right = null;}}class BinaryTree {Node root;void iterativePreorder(){iterativePreorder(root);}// An iterative process to print preorder traversal of Binary treevoid iterativePreorder(Node node) {// Base Caseif (node == null) {return;}// Create an empty stack and push root to itStack<Node> nodeStack = new Stack<Node>();nodeStack.push(root);/* Pop all items one by one. Do following for every popped itema) print itb) push its right childc) push its left childNote that right child is pushed first so that left is processed first */while (nodeStack.empty() == false) {// Pop the top item from stack and print itNode mynode = nodeStack.peek();System.out.print(mynode.data + " ");nodeStack.pop();// Push right and left children of the popped node to stackif (mynode.right != null) {nodeStack.push(mynode.right);}if (mynode.left != null) {nodeStack.push(mynode.left);}}}}public class main{// driver program to test above functionspublic static void main(String args[]) {BinaryTree tree = new BinaryTree();tree.root = new Node(10);tree.root.left = new Node(8);tree.root.right = new Node(2);tree.root.left.left = new Node(3);tree.root.left.right = new Node(5);tree.root.right.left = new Node(2);tree.iterativePreorder();}}

这里用了一个栈的数据结构,先把根入栈,然后打印根值,根出栈,押入右子节点,再押入左子节点,循环直到空栈,这个比较好理解,不多解释了

原创粉丝点击