/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/publicclassCodec{// 知识点:String、StringBuilder、parseInt的处理// Encodes a tree to a single string.publicStringserialize(TreeNode root){if(root ==null){return"[]";}StringBuilder res =newStringBuilder("[");Queue<TreeNode> queue =newLinkedList<>();queue.add(root);// 层序遍历 BFS(迭代) while(!queue.isEmpty()){TreeNode temp = queue.poll();if(temp !=null){// 当前值加入 res,子结点加入 queueres.append(temp.val).append(",");queue.add(temp.left);queue.add(temp.right);}// 空结点 情况else{res.append("null,");}}// 删除末尾的','res.delete(res.length()-1, res.length());res.append("]");return res.toString();}// Decodes your encoded data to tree.publicTreeNodedeserialize(String data){if(data.equals("[]")){returnnull;}// 1. initString[] vals = data.substring(1, data.length()-1).split(",");TreeNode root =newTreeNode(Integer.parseInt(vals[0]));Queue<TreeNode> queue =newLinkedList<>();queue.add(root);// 2. deserializefor(int i =1;!queue.isEmpty(); i +=2){TreeNode temp = queue.poll();// 左结点判断if(!vals[i].equals("null")){temp.left =newTreeNode(Integer.parseInt(vals[i]));queue.add(temp.left);}// 右结点判断if(!vals[i +1].equals("null")){temp.right =newTreeNode(Integer.parseInt(vals[i +1]));queue.add(temp.right);}}return root;}}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.deserialize(codec.serialize(root));
文章目录题目描述思路 && 代码二刷一脸懵逼,居然没写这道题的题解。。 题目描述 思路 && 代码
思路:平衡二叉树判断公式 左子树满足 右子树满足 左右子树高度差不超过1
/*** Definition for a binary tree node.* public class Tre…