首页 > 其他 > 详细

二叉树的建立,非递归中序,后序,先序

时间:2021-05-18 23:13:16      阅读:21      评论:0      收藏:0      [点我收藏+]
import java.util.LinkedList;
import java.util.Scanner;

class TreeNode{
    char val;
    TreeNode leftchild;
    TreeNode rightchild;
    int flag;//用于后续非递归
}
public class Tree {
    Scanner scanner= new Scanner(System.in);
    public TreeNode buildNode()
    {
        char s=scanner.next().charAt(0);
        if(s==‘#‘) return null;
        TreeNode node= new TreeNode();
        node.val=s;
        node.leftchild=buildNode();
        node.rightchild=buildNode();
        return node;
    }
    public TreeNode buildTree()
    {
        TreeNode root=new TreeNode();
        root.val=scanner.next().charAt(0);
        root.leftchild=buildNode();
        root.rightchild=buildNode();
        return root;
    }
    public void output(TreeNode root)
    {
        if(root==null)return;
        System.out.print(root.val+" ");
        output(root.leftchild);
        output(root.rightchild);
    }
/**
 * ///测试数据
a
b
d
#
#
e
#
#
c
f
#
#
#
 **///中序
    public void NoRecurInnerOder(TreeNode root)
    {
        LinkedList<TreeNode> stack= new LinkedList<>();
        TreeNode cur=root;
        while (cur!=null||!stack.isEmpty())
        {
            while (cur!=null)
            {
                stack.push(cur);
                cur=cur.leftchild;
            }
            if(stack.isEmpty())break;
            cur=stack.pop();
            System.out.print(cur.val+" ");
            cur=cur.rightchild;
        }
    }//先序
    public void NoRecurPreOrder(TreeNode root)
    {
        LinkedList<TreeNode> stack= new LinkedList<>();
        TreeNode cur=root;
        cur=root;
        while (cur!=null||!stack.isEmpty())
        {
            while (cur!=null)
            {
                System.out.print(cur.val+" ");
                stack.push(cur);
                cur=cur.leftchild;
            }
            if(stack.isEmpty())break;
            cur=stack.pop();
            cur=cur.rightchild;
        }
    }//后序
    public void NoRecurPostOrder(TreeNode root)
    {
        TreeNode cur;
        LinkedList<TreeNode> stack= new LinkedList<>();
        cur=root;
        while (cur!=null||!stack.isEmpty())
        {
            while (cur!=null)
            {
                stack.push(cur);
                cur=cur.leftchild;
            }
            if(stack.peek().flag==1)
            {
                System.out.print(stack.pop().val+" ");
            }else {
                if (stack.isEmpty()) break;
                stack.peek().flag = 1;
                cur = stack.peek().rightchild;
            }
        }
    }
    public static void main(String[] args) {
        Tree tree=new Tree();
        TreeNode root= tree.buildTree();
        tree.NoRecurPostOrder(root);
    }
}

二叉树的建立,非递归中序,后序,先序

原文:https://www.cnblogs.com/AI-Creator/p/14782926.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!