二叉树遍历(栈方式)[非递归]

    xiaoxiao2022-07-07  162

    参考:程序员小灰

    前序遍历:

    package chapter3.part2; import java.util.Arrays; import java.util.LinkedList; import java.util.Stack; import org.junit.Test; public class BinaryTreeFindWithStack { @Test public void printBTWithStack() { LinkedList<Integer> inputList = new LinkedList<Integer>(Arrays. asList(new Integer[] {3,2,9,null,null,10,null,null,8,null,4})); TreeNode root = createBinary(inputList); printBinaryTree(root); } private void printBinaryTree(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode node = root; while(node != null || !stack.isEmpty()) {//node判断的是结点对象,stack.isEmpty()判断的是栈的元素个数 while(node != null) { System.out.println(node.data); stack.push(node); node = node.leftNode; } if(stack != null) { node = stack.pop();//注意这里,栈返回的是 被弹出的结点 node = node.rightNode; } } } private TreeNode createBinary(LinkedList<Integer> inputList) { TreeNode node = null; if(inputList == null || inputList.isEmpty()) {//inputList ==null判断的是对象,inputList.isEmpty()判断的是元素个数 return null; } Integer data = inputList.removeFirst(); if(data != null) { node = new TreeNode(data); node.leftNode = createBinary(inputList); node.rightNode = createBinary(inputList); } return node; } }

     

    需要注意的是:node != null判断的是结点对象,stack.isEmpty()判断的是栈的元素个数是否为0,

    stack.pop()返回的是被弹出的结点,

    inputList == null 判断的是inputList的对象是否为空,inputList.isEmpty()判断的是inputList中的元素个数是否为0

    Integer[] {3,2,9,null,null,10,null,null,8,null,4},注意这个数组中的null,及其构建起来的二叉树的样子。


    中序遍历:

    private void printBinaryTree(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode node = root; while(node != null || !stack.isEmpty()) { while(node != null) { stack.push(node); node = node.leftNode; } if(stack != null) { node = stack.pop(); System.out.println(node.data);//中序遍历 node = node.rightNode; } } }


    后序遍历:

    待写。。。

     

     

    最新回复(0)