二叉树的非递归实现(先,中,后)

来源:互联网 发布:mac ftp下载工具 编辑:程序博客网 时间:2024/05/27 12:21

先序

public void xianxu(TreeNode root)  {   if(root == null) return ;   stack.push(root);   while(!stack.isEmpty()){    TreeNode tmp =stack.pop();    System.out.print(tmp.val+" ");    if(tmp.right!=null) stack.push(tmp.right);    if(tmp.left!=null) stack.push(tmp.left);   }}

中序

 public static void zhongxu(TreeNode root){      TreeNode cur =root;      stack.push(cur);      cur = cur.left;      while(!stack.isEmpty() || cur !=null){        if(cur!= null){        stack.push(cur);        cur =cur.left;        }else{        cur =stack.pop();        System.out.print(cur.val+" ");            cur = cur.right;        }      }          }

后序

public static void houxu(TreeNode root){               if(root == null)return ;               TreeNode cur =root;               stack1.push(cur);               while(!stack1.isEmpty()){                      cur = stack1.pop();                      stack2.push(cur);                      if(cur.left != null){                      stack1.push(cur.left);                      }                      if(cur.right != null){                      stack1.push(cur.right);                      }               }               while(!stack2.isEmpty()){                 cur =stack2.pop();                 System.out.print(cur.val+" ");               }}


0 0
原创粉丝点击