标签:tree ring stat util rod list sys pos order
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);
}
}
标签:tree ring stat util rod list sys pos order
原文地址:https://www.cnblogs.com/AI-Creator/p/14782926.html