JZ78 把二叉树打印成多行 ⭐ ⭐
层序遍历
public class Solution {
public ArrayList<ArrayList<Integer>> Print (TreeNode pRoot) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>> ( );
LinkedList<TreeNode> qu = new LinkedList<>();
if (pRoot == null) return ans;
else {
qu.offer(pRoot);
while (!qu.isEmpty()) {
ArrayList<Integer> list = new ArrayList<Integer> ();
for (int i = qu.size(); i > 0; i--) {
TreeNode t = qu.removeFirst();
list.add(t.val);
if (t.left != null) qu.addLast(t.left);
if (t.right != null) qu.addLast(t.right);
}
ans.add(list);
}
return ans;
}
}
}
JZ37 序列化二叉树 ⭐ ⭐⭐ 24%
序列化与反序列化,序列化使用递归,反序列化用一个队列保存节点信息
public class Solution {
String Serialize(TreeNode root) {
if (root == null) return "#";
return root.val + "," + Serialize(root.left) + "," + Serialize(root.right);
}
TreeNode Deserialize(String str) {
Queue<String> qu = new LinkedList<>(Arrays.asList(str.split(",")));
return build(qu);
}
public TreeNode build(Queue<String> qu) {
String s = qu.poll();
if ("#".equals(s)) return null;
TreeNode root = new TreeNode(Integer.parseInt(s));
root.left = build(qu);
root.right = build(qu);
return root;
}
}