首页 > 代码库 > 二叉树后序非递归遍历
二叉树后序非递归遍历
package com.basic.bt; import java.util.ArrayList; import java.util.Stack; /** * Created by mac on 2017/1/19. */ public class PostOrderBT { ArrayList<Integer> result = new ArrayList<Integer>(); public void postorder(TreeNode root) { if(root == null) { return; } postorder(root.left); postorder(root.right); result.add(root.val); } public void postOrderTraversal(TreeNode root) { if(root == null) { return; } Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode node = root; TreeNode pre = null; while( node != null || !stack.isEmpty()) { while(node != null) { stack.push(node); node = node.left; } // node指向了空,所以要pop()一下 另外也是出于 对node右孩子的考虑; node = stack.pop(); while( node != null && (node.right == null || node.right == pre)) { result.add(node.val); pre = node; if(stack.isEmpty()) { return; } node = stack.pop(); } stack.push(node); node = node.right; } } public static void main(String[] args) { PostOrderBT in = new PostOrderBT(); TreeNode root = new TreeNode(0); TreeNode node1 = new TreeNode(1); TreeNode node2 = new TreeNode(2); TreeNode node3 = new TreeNode(3); TreeNode node4 = new TreeNode(4); root.left = node1; root.right = node2; node1.left = node3; node1.right =node4; in.postOrderTraversal(root); for(int i = 0; i < in.result.size(); i++) { System.out.println(in.result.get(i)); } } }
二叉树后序非递归遍历
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。