您好,欢迎访问一九零五行业门户网

关于二叉树的非递归遍历实例代码分享

二叉树的非递归遍历是怎么样的?二叉树的非递归遍历也是采用的是递归的思想,拿前序遍历为例:先通过找到最左下角的节点,然后将其输出,并且对此节点的右子树再进行下一步的操作。
前序遍历:
public void pre_iteration(node p) {if (p == null) return; stack<node> stack = new stack<>();while (!stack.isempty() || p != null) {while (p != null) { system.out.println(p.val); stack.push(p); p = p.left; }if (!stack.isempty()) { p = stack.pop(); p = p.right; } } }
中序遍历:
public void in_iteration(node p) {if (p == null) return; stack<node> stack = new stack<>();while (!stack.isempty() || p != null) {while (p != null) { stack.push(p); p = p.left; }if (!stack.isempty()) { p = stack.pop(); system.out.println(p.val); p = p.right; } } }
后序遍历:(stack2是用来记载当前节点的右子树是否已经被遍历过)
public static void post_iteration(node p) {if (p == null) return; stack<node> stack = new stack<>(); stack<boolean> stack2 = new stack<>();while (!stack.isempty() || p != null) {while (p != null) { stack.push(p); stack2.push(false); p = p.left; }while (!stack.isempty() && stack2.peek()) { system.out.println(stack.pop().val); stack2.pop(); }if (!stack.isempty()) { p = stack.peek().right; stack2.pop(); stack2.push(true); } } }
以上就是关于二叉树的非递归遍历实例代码分享的详细内容。
其它类似信息

推荐信息