树的遍历(前序,中序,后续,栈与递归实现)
2017-07-24 21:50
281 查看
树的定义
public class TreeNode { public TreeNode left; public TreeNode right; public int val; public TreeNode(int val){ this.val=val; this.left=null; this.right=null; } }
前序遍历
public void preorderStack(TreeNode root) { Stack<TreeNode> stack=new Stack<>(); while(root!=null || !stack.isEmpty()){ while(root!=null){ stack.push(root); System.out.println(root.val); root=root.left; } root=stack.pop(); root=root.right; } } public void preOrder(TreeNode root){ if(root!=null){ System.out.println(root.val); preOrder(root.left); preOrder(root.right); } }
中序遍历
public void inorderStack(TreeNode root) { Stack<TreeNode> stack=new Stack<>(); while(root!=null || !stack.isEmpty()){ while(root!=null){ stack.push(root); root=root.left; } root=stack.pop(); System.out.println(root.val); root=root.right; } } public void inOrder(TreeNode root){ if(root!=null){ inOrder(root.left); System.out.println(root.val); inOrder(root.right); } }
后序遍历
public void postorderStack(TreeNode root){ Stack<TreeNode>stack=new Stack<>(); Map<TreeNode, Boolean> map=new HashMap<>(); stack.push(root); while(!stack.isEmpty()){ TreeNode node=stack.peek(); if(node.left!=null && !map.containsKey(node.left)){ node=node.left; while(node!=null){ if(map.containsKey(node))break; stack.push(node); node=node.left; } continue; } if(node.right!=null && !map.containsKey(node.right)){ stack.push(node.right); continue; } TreeNode t=stack.pop(); map.put(t, true); System.out.println(t.val); } } public void postOrder(TreeNode root){ if(root!=null){ postOrder(root.left); postOrder(root.right); System.out.println(root.val); } }
相关文章推荐
- 二叉树的前序、中序、后续遍历,递归、非递归实现
- 二叉树遍历算法(递归实现先序中序和后续遍历)(非递归实现中序和先续)
- 二叉树前序、中序、后续遍历(递归实现)
- 二叉树的前序,中序,后续,递归及非递归遍历的python实现
- 二叉树先序、中序、后续遍历递归以及非递归java实现
- Java实现树的遍历(前序、中序、后续(递归|非递归)、层次)
- 二叉树的实现&&递归和非递归方式前序、中序、后续遍历&&发现一个节点中序遍历的下一节点
- Java 二叉树的前序、中序、后续遍历 递归和迭代实现
- 二叉树先序、中序、后续遍历(非递归实现)
- 递归和非递归俩种方法实现二叉树的前序、中序、后续遍历
- 二叉树构建,先序,中序,后序遍历(以及非递归实现),广度优先遍历
- 用递归和非递归方式实现二叉树先序、中序和后序遍历
- 数据结构/实现二叉树的前序/中序/后序非递归遍历
- 再回首,数据结构——树的先序、中序、后序遍历的递归与非递归实现
- 二叉树先序、中序,后序遍历的递归和非递归实现
- 二叉树先序、中序、后序遍历的非递归实现
- 二叉树的遍历:前序,中序,后序,层序--包括递归和非递归实现
- 二叉树的前序、中序、后序及层次遍历的递归与非递归源码实现
- 二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 求后续遍历(递归实现)