1086. Tree Traversals Again (25)
题目链接:
http://pat.zju.edu.cn/contests/pat-a-practise/1086
结题思路:
根据输入,构建二叉树。
每当一行读入为Push,就在new一个节点给父节点对应的儿子。
没当一行读入为Pop ,就返回null给父节点对应的儿子。
核心代码(构建二叉树):
public static Node buildTree(){
Node node =null;
if(count <2*n){
String line =sc.nextLine().trim();
if(line.startsWith("Push")){
int value =Integer.parseInt(line.split(" ")[1]);
node =instance.new Node(value);
count++;
}
else{
count++;
return null;
}
node.setLeft(buildTree());
node.setRight(buildTree());
}
return node;
}
构建树完毕,后续遍历二叉树。
Java 代码:
import java.util.Scanner;
import java.util.Stack;
public class Main {
static Main instance =new Main();
static Scanner sc =new Scanner(System.in);
static String currentLine;
static int n ,count =0;
static Stack<Node> stack =new Stack<Node>();
static StringBuilder sbd =new StringBuilder();
public static void main(String[] arg){
n = Integer.parseInt(sc.nextLine().trim());
Node root =buildTree();
followUpTraversal(root);
System.out.print(sbd.toString().trim());
}
public static Node buildTree(){
Node node =null;
if(count <2*n){
String line =sc.nextLine().trim();
if(line.startsWith("Push")){
int value =Integer.parseInt(line.split(" ")[1]);
node =instance.new Node(value);
count++;
}
else{
count++;
return null;
}
node.setLeft(buildTree());
node.setRight(buildTree());
}
return node;
}
public static void followUpTraversal(Node node){
if(node.getLeft()!=null){
followUpTraversal(node.getLeft());
}
if(node.getRight()!=null){
followUpTraversal(node.getRight());
}
sbd.append(node.getValue()+" ");
}
class Node{
int value;
Node left;
Node right;
public Node(int val){
value =val;
left =null;
right =null;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
}
}
C++代码:
#include <stdio.h>
struct Node
{
int val;
Node *left;
Node *right;
Node(int v):val(v),left(NULL),right(NULL){}
Node(){}
};
char input[8];
int n=0,ids=0,ids2=0;
Node * buildTree()
{
Node * r=NULL;
int tmp=0;
if(ids<2*n)
{
scanf("%s",input);
if(input[1]=='u')
{
scanf("%d",&tmp);
r = new Node(tmp);
ids++;
}else if(input[1]=='o')
{
ids++;
return NULL;
}
r->left = buildTree();
r->right = buildTree();
}
return r;
}
void postorder(Node *r)
{
if(r!=NULL)
{
postorder(r->left);
postorder(r->right);
printf("%d",r->val);
ids2++;
if(ids2<n){
printf(" ");
}else
{
printf("\n");
}
}
}
int main()
{
scanf("%d",&n);
Node * root = buildTree();
postorder(root);
return 0;
}
C++代码出处:
http://blog.csdn.net/nan327347465/article/details/39104489