二叉树的前/中/后序遍历算法(非递归)

来源:互联网 发布:魏晨全球歌迷会淘宝网 编辑:程序博客网 时间:2024/06/15 17:55

都由堆栈实现,如下:

先序:

public List<Integer> preorderTraversal(TreeNode root) {    Stack<TreeNode> stack=new Stack();    TreeNode rot=root;    List<Integer> list=new ArrayList();    while(rot!=null||!stack.empty())    {        if(rot!=null)        {            list.add(rot.val);            stack.push(rot);            rot=rot.left;        }        else        {            rot=stack.pop().right;        }    }    return list;}

中序:

public List<Integer> inorderTraversal(TreeNode root) {    Stack<TreeNode> stack=new Stack();    List<Integer> list=new ArrayList();    TreeNode rot=root;    while(!stack.isEmpty()||rot!=null)    {        while(rot!=null)        {            stack.push(rot);            rot=rot.left;        }        TreeNode t1=stack.pop();        list.add(t1.val);        rot=t1.right;    }    return list;}
后序:
public List<Integer> postorderTraversal(TreeNode root) {    List<Integer> list=new ArrayList();    Stack<TreeNode> stack=new Stack();    TreeNode current=root;    TreeNode previsit=null;    while(!stack.isEmpty()||current!=null)    {        while(current!=null)        {            stack.push(current);            current=current.left;        }        current=stack.peek();        if(current.right==null||current.right==previsit)        {            list.add(current.val);            stack.pop();            previsit=current;            current=null;        }        else        {            current=current.right;        }    }    return list;}


0 0
原创粉丝点击