【PAT】1086. Tree Traversals Again (25)

import java.util.Scanner;

class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;

	TreeNode(int val) {
		this.val = val;
	}
}
/**
 * 
 *
 结题思路:

根据输入,构建二叉树。
每当一行读入为Push,就在new一个节点给父节点对应的儿子。
每当一行读入为Pop ,就返回null给父节点对应的儿子。
 */
public class Main {
	static Scanner input = new Scanner(System.in);
	private static int n;
	private static int count = 0;
	private static StringBuffer resultBuffer = new StringBuffer();

	public static void postorder(TreeNode root) {
		if (root != null) {
			postorder(root.left);
			postorder(root.right);
			resultBuffer.append(root.val + " ");
		}
	}

	//创建一棵树,然后返回它的根节点
	public static TreeNode buildTree() {
		TreeNode node = null;
		if (count < 2 * n) {
			String line = input.nextLine().trim();
			if (line.startsWith("Push")) {
				int value = Integer.parseInt(line.split(" ")[1]);
				node = new TreeNode(value);
				count++;
			} else {
				count++;
				return null;

			}
			node.left = buildTree();
			node.right = buildTree();
		}
		return node;
	}

	public static void main(String[] args) {
		//当nextint和nextlne一起用的时候会出错,全部都用nextline
		n = Integer.parseInt(input.nextLine().trim());
		TreeNode rootNode = buildTree();
		postorder(rootNode);
		System.out.println(resultBuffer.toString().trim());
	}
}

你可能感兴趣的:(JAVA,About,Offer)