LeetCode二叉树完整输入输出
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; /** * 二叉树的题目:包括建树的过程 */ /* Definition for a binary tree nod */ class TreeNode { int val; TreeNode left; TreeNode right; public TreeNode() { } public TreeNode(int val) { this.val = val; } public TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } // 翻转二叉树 class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) return root; Queue<TreeNode> que = new LinkedList<>(); que.offer(root); while (!que.isEmpty()) { TreeNode temp = que.poll(); TreeNode left = temp.left, right = temp.right; temp.left = right; temp.right = left; if (left != null) que.offer(left); if (right != null) que.offer(right); } return root; } } public class leetcode { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = in.readLine()) != null) { // 读入多行 以Enter键分隔 TreeNode root = stringToTreeNode(line); TreeNode ret = new Solution().invertTree(root); String output = treeNodeToString(ret); System.out.println(output); } } // 建树:将输入的字符串转换为TreeNode eg [4,2,7,1,3,6,9] public static TreeNode stringToTreeNode(String input) { input = input.trim(); // 去除首尾的空格 input = input.substring(1, input.length() - 1); // 去除首尾的'[' if (input.length() == 0) { return null; } String[] parts = input.split(","); String item = parts[0]; item = item.trim(); TreeNode root = new TreeNode(Integer.parseInt(item)); // 使用优先队列进行层序遍历 Queue<TreeNode> nodeQueue = new LinkedList<>(); nodeQueue.add(root); int index = 1; while (!nodeQueue.isEmpty()) { TreeNode node = nodeQueue.remove(); if (index == parts.length) { break; } // 取左子节点 item = parts[index++]; item = item.trim(); if (!"null".equals(item)) { int leftNumber = Integer.parseInt(item); node.left = new TreeNode(leftNumber); nodeQueue.add(node.left); } if (index == parts.length) { break; } // 取右子节点 item = parts[index++]; item = item.trim(); if (!"null".equals(item)) { int rightNumber = Integer.parseInt(item); node.right = new TreeNode(rightNumber); nodeQueue.add(node.right); } } return root; } // 输出:以String的方式输出 // String s=new StringBuilder().append(new String("abc")).append(new String("def")).toString(); public static String treeNodeToString(TreeNode root) { if (root == null) return "[]"; String output = ""; Queue<TreeNode> nodeQueue = new LinkedList<>(); nodeQueue.add(root); while (!nodeQueue.isEmpty()) { TreeNode node = nodeQueue.remove(); if (node == null) { output += "null, "; continue; } output += String.valueOf(node.val) + ", "; nodeQueue.add(node.left); nodeQueue.add(node.right); } return "[" + output.substring(0, output.length() - 2) + "]"; // 将最后一个数字后的','和' '去掉 } }
作者:Ryanjie
出处:http://www.cnblogs.com/ryanjan/
本文版权归作者和博客园所有,欢迎转载。转载请在留言板处留言给我,且在文章标明原文链接,谢谢!
如果您觉得本篇博文对您有所收获,觉得我还算用心,请点击右下角的 [推荐],谢谢!