赞
踩
目录
- public class TreeNode {
- char val;
- TreeNode left;
- TreeNode right;
- public TreeNode(char val) {
- this.val = val;
- }
- }
- public class TestBinaryTree {
- //前序遍历-非递归
- public preOrderTraversalNor (TreeNode root) {
- if (root == null) return;
- Stack<TreeNode> stack = new Stack<>();
- TreeNode cur = root;
-
- while (cur != null || !stack.empty()) {
- while (cur != null) {
- stack.push(cur);
- System.out.println(cur.val + " ");
- cur = cur.left;
- }
- //当cur.left为空时,弹栈
- TreeNode top = stack.pop();
- cur = top.right; //1.null 2.不是null的情况
- }
- }
- }
- void inOrderTraversalNor (TreeNode root) {
- if (root == null) return;
- Stack<TreeNode> stack = new Stack<>();
- TreeNode cur = root;
-
- while (cur != null || !stack.empty()) {
- while (cur != null) {
- stack.push(cur);
- cur = cur.left;
- }
- //当cur==null,说明走到了二叉树的最左侧,开始弹栈并打印
- TreeNode top = stack.pop();
- System.out.print(top.val+" ");
- cur = top.right;
- }
- System.out.println();
- }
主要注意解决cur当前结点被打印 和 cur的右侧结点已被打印的问题
- void postOrderTraversalNor(TreeNode root) {
- if (root == null) return;
- Stack<TreeNode> stack = new Stack<>();
- TreeNode prev = null;
- TreeNode cur = root;
- while ( cur != null || !stack.empty()) {
- while ( cur != null) {
- stack.push(cur);
- cur = cur.left;
- }
- //走到最左边了
- cur = stack.peek();
- if (cur.right == null || cur.right == prev) { //cur.right == prev表明右结点被打印过了
- stack.pop();
- System.out.print(cur.val+" ");
- //记录被打印过的结点
- prev = cur;
- cur = null; //打印完一定要置空
- } else {
- cur = cur.right;
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。