二叉树的递归遍历算法很简单,而非递归遍历算法中的先序和中序遍历相比于后序遍历更简单一点,在这先实现先序和中序遍历的非递归算法。
先序遍历代码如下:
public static void preOrder(TreeNode root) {
TreeNode current = root;
Stack<TreeNode> stack = new Stack<TreeNode>();
while(current!=null || !stack.isEmpty()) {
if(current!=null) {
System.out.println(current.val);
stack.push(current);
current = current.left;
}
else {
current = stack.pop();
current = current.right;
}
}
}
中序遍历代码如下:
public static void inOrder(TreeNode root) {
TreeNode current = root;
Stack<TreeNode> stack = new Stack<TreeNode>();
while(current!=null || !stack.isEmpty()) {
if(current!=null) {
stack.push(current);
current = current.left;
}
else {
current = stack.pop();
System.out.println(current.val);
current = current.right;
}
}
}
对比先序遍历和中序遍历,我们可以发现,这两者之间的本质区别在于,先序遍历是入栈之前先访问,而中序遍历是出栈的时候才访问。就代码上的区别来看,不过是把if中push之前的System.out.println(current.val)挪到了else语句块中的pop之后。