递归
//递归先序遍历 public static void pre(TreeNode root){ if(root==null) return; visit(root); if(root.left!=null) pre(root.left); if(root.right!=null) pre(root.right); } //递归中序遍历 public static void in(TreeNode root) { if(root == null)return; if(root.left!=null)in(root.left); visit(root); if(root.right!= null)in(root.right); } //递归后序遍历 public static void post(TreeNode root) { if(root == null)return; if(root.left!=null)in(root.left); if(root.right!= null)in(root.right); visit(root); }
非递归:
//非递归前序遍历--栈 public static void preTraverse(TreeNode root){ Stack<TreeNode> s=new Stack<TreeNode>(); s.push(root); while(!s.isEmpty()){ TreeNode current=s.pop(); visit(current); if(current.right!=null) s.push(current.right); if(current.left!=null) s.push(current.left); } } //非递归前序遍历--队列 public static void preTraverse2(TreeNode root){ Queue<TreeNode> q=new LinkedList<TreeNode>(); q.offer(root); while(!q.isEmpty()){ TreeNode current=q.poll(); visit(current); if(current.left!=null) q.offer(current.left); if(current.right!=null) q.offer(current.right); } } //非递归中序遍历 public static void inTraverse(TreeNode root){ Stack<TreeNode> s=new Stack<TreeNode>(); TreeNode t=root; while(!s.isEmpty()||t!=null){ if(t!=null){ s.push(t); t=t.left; }else{ t=s.pop(); visit(t); t=t.right; } } }
时间: 2024-11-09 11:02:43