非递归遍历二叉树Java实现

2018-10-03 20:16:53

非递归遍历二叉树是使用堆栈来进行保存,个人推荐使用双while结构,完全按照遍历顺序来进行堆栈的操作,当然在前序和后序的遍历过程中还有其他的压栈流程。

一、Binary Tree Preorder Traversal

问题描述:

问题求解:

先序遍历就是在第一次访问到节点的时候将其值进行打印,然后递归打印其左子树,最后递归打印其右子树。

解法一、双while

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                res.add(root.val);
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            root = root.right;
        }
        return res;
    }

解法二、

可以使用一个栈来模拟这种操作:

首先将root压栈;

每次从堆栈中弹出栈顶元素,表示当前访问的元素,对其进行打印;

依次判断其右子树,左子树是否非空,并进行压栈操作,至于为什么先压栈右子树,因为先压栈的后弹出,左子树需要先访问,因此后压栈;

重复直到栈为空。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        if (root == null) return new ArrayList<>();
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            res.add(cur.val);
            if (cur.right != null) stack.push(cur.right);
            if (cur.left != null) stack.push(cur.left);
        }
        return res;
    }
}

二、Binary Tree Inorder Traversal

问题描述:

问题求解:

双while大法。

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }

三、Binary Tree Postorder Traversal

问题描述:

问题求解:

后序遍历的非递归版本是最有技巧性的,难度相对高一点,但其实是可以转换成前序遍历的。

后序遍历的顺序是左右中,因此只需要按中右左遍历,再reverse一下即可。

解法一、双while大法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                res.add(0, root.val);
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            root = root.right;
        }
        return res;
    }
}

解法二、

    public List<Integer> postorderTraversal(TreeNode root) {
        if (root == null) return new ArrayList<>();
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            res.add(0, cur.val);
            if (cur.left != null) stack.add(cur.left);
            if (cur.right != null) stack.add(cur.right);
        }
        return res;
    }

原文地址:https://www.cnblogs.com/TIMHY/p/9740814.html

时间: 2024-08-14 09:23:37

非递归遍历二叉树Java实现的相关文章

JAVA递归、非递归遍历二叉树(转)

原文链接: JAVA递归.非递归遍历二叉树 import java.util.Stack; import java.util.HashMap; public class BinTree { private char date; private BinTree lchild; private BinTree rchild; public BinTree(char c) { date = c; } // 先序遍历递归 public static void preOrder(BinTree t) {

史上最简明易懂非递归遍历二叉树算法

巧若拙(欢迎转载,但请注明出处:http://blog.csdn.net/qiaoruozhuo) 遍历二叉树的递归函数是体现了算法之美的高妙算法,思路清晰,代码简洁,读之赏心悦目.代码例如以下: 程序代码: void PreOrderTraverse_R(BiTree BT)//採用递归方式先序遍历二叉树BT { if(BT != NULL) { printf("%c", BT->data);//输出该结点(根结点) PreOrderTraverse_R(BT->lchi

【转】更简单的非递归遍历二叉树的方法

解决二叉树的很多问题的方案都是基于对二叉树的遍历.遍历二叉树的前序,中序,后序三大方法算是计算机科班学生必写代码了.其递归遍历是人人都能信手拈来,可是在手生时写出非递归遍历恐非易事.正因为并非易事,所以网上出现无数的介绍二叉树非递归遍历方法的文章.可是大家需要的真是那些非递归遍历代码和讲述吗?代码早在学数据结构时就看懂了,理解了,可为什么我们一而再再而三地忘记非递归遍历方法,却始终记住了递归遍历方法? 三种递归遍历对遍历的描述,思路非常简洁,最重要的是三种方法完全统一,大大减轻了我们理解的负担.

重拾算法(1)——优雅地非递归遍历二叉树及其它

重拾算法(1)——优雅地非递归遍历二叉树及其它 本文中非递归遍历二叉树的思想和代码都来自这里(http://jianshu.io/p/49c8cfd07410#).我认为其思想和代码都足够优雅动人了,于是稍作整理,得到如下的程序. 前中后序遍历二叉树 1 public class BinaryTreeNode<T> 2 { 3 public T Value { get;set; } 4 public BinaryTreeNode<T> Parent { get;set; } 5 p

非递归遍历二叉树的前序中序后序

/** * 二叉树先序遍历,非递归算法 * 1.申请一个新的栈,记为stack.然后将头节点head压入stack中. * 2.从stack弹出栈顶节点,记为cur,然后打印cur节点的值,再将cur右孩子(不为空) * 压入stack中,最后将cur的左孩子(不为空)压入stack中 * 3.不断重复步骤2,直到stack为空,全部过程结束. * @param head */ public void preOrderNoRecur(Node head){ System.out.print("非

非递归遍历二叉树之中序遍历

//中序遍历int inorder_tree_walk(BinTreeNode * root){ if(root == NULL){ return -1; } stack<BinTreeNode *> s; BinTreeNode * p = root; while(!s.empty() || p != NULL) { while(p != NULL){ s.push(p); p = p->lchild; } p = s.top(); s.pop(); cout << p-&

非递归遍历二叉树之前序遍历

前序遍历二叉树 int preorder_tree_walk(BinTreeNode * root){ if(root == NULL){ return -1; } stack<BinTreeNode *> s; BinTreeNode * p = root; while(!s.empty() || p != NULL) { while(p != NULL){ cout << p->key<< endl; s.push(p); p = p->lchild;

非递归遍历二叉树

#include <stack> #include <stdio.h> #include <malloc.h> #include <iostream> using namespace std; typedef struct node { int flag; char value; struct node *lchild; struct node *rchild; }Node, *PNode; void CreateBinaryTree(PNode &

非递归遍历二叉树【层次遍历,先序、中序、后序遍历】

一.层次遍历:借助队列实现 1 void LevelOrderTraversal(BiTree root) 2 { 3 BiTree e = root;//从根节点开始 4 Queue *q; 5 InitQueue(q); 6 7 if(e)//若根结点非空,则入队列 8 { 9 EnQueue(q,e); 10 } 11 12 while(!QueueEmpty(q)) 13 { 14 DelQueue(q,e); 15 Visit(e); 16 if(e->leftChild)//左孩子不