诸神缄默不语-个人CSDN博文目录
力扣刷题笔记
Python3版代码提示:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None# Your Codec object will be instantiated and called as such:
# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# tree = ser.serialize(root)
# ans = deser.deserialize(tree)
# return ans
Java版代码提示:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// String tree = ser.serialize(root);
// TreeNode ans = deser.deserialize(tree);
// return ans;
我真的忘的一干二净,就是有那么一点点熟悉,但是写起来又一脸懵逼。
直接抄题解。
文章目录
- 1. 后序遍历
- 2. 先序遍历
1. 后序遍历
seriallize就是常规的后序遍历(左→右→根)。
deserialize根据二叉搜索树的特性,递归反序列化根节点→右子树(直至接下来需要反序列化的节点值<根节点值)→左子树(直至接下来需要反序列化的节点值>根节点值)
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( n ) O(n) O(n)
Python3版:
class Codec:def serialize(self, root: TreeNode) -> str:arr = []def postOrder(root: TreeNode) -> None:if root is None:returnpostOrder(root.left)postOrder(root.right)arr.append(root.val)postOrder(root)return ' '.join(map(str, arr))def deserialize(self, data: str) -> TreeNode:arr = list(map(int, data.split()))def construct(lower: int, upper: int) -> TreeNode:if arr == [] or arr[-1] < lower or arr[-1] > upper:return Noneval = arr.pop()root = TreeNode(val)root.right = construct(val, upper)root.left = construct(lower, val)return rootreturn construct(-inf, inf)
Java版:
public class Codec {public String serialize(TreeNode root) {List<Integer> list = new ArrayList<Integer>();postOrder(root, list);String str = list.toString();return str.substring(1, str.length() - 1);}public TreeNode deserialize(String data) {if (data.isEmpty()) {return null;}String[] arr = data.split(", ");Deque<Integer> stack = new ArrayDeque<Integer>();int length = arr.length;for (int i = 0; i < length; i++) {stack.push(Integer.parseInt(arr[i]));}return construct(Integer.MIN_VALUE, Integer.MAX_VALUE, stack);}private void postOrder(TreeNode root, List<Integer> list) {if (root == null) {return;}postOrder(root.left, list);postOrder(root.right, list);list.add(root.val);}private TreeNode construct(int lower, int upper, Deque<Integer> stack) {if (stack.isEmpty() || stack.peek() < lower || stack.peek() > upper) {return null;}int val = stack.pop();TreeNode root = new TreeNode(val);root.right = construct(val, upper, stack);root.left = construct(lower, val, stack);return root;}
}
2. 先序遍历
class Codec:def serialize(self, root: Optional[TreeNode]) -> str:"""Encodes a tree to a single string."""def dfs(root: Optional[TreeNode]):if root is None:returnnums.append(root.val)dfs(root.left)dfs(root.right)nums = []dfs(root)return " ".join(map(str, nums))def deserialize(self, data: str) -> Optional[TreeNode]:"""Decodes your encoded data to tree."""def dfs(mi: int, mx: int) -> Optional[TreeNode]:nonlocal iif i == len(nums) or not mi <= nums[i] <= mx:return Nonex = nums[i]root = TreeNode(x)i += 1root.left = dfs(mi, x)root.right = dfs(x, mx)return rootnums = list(map(int, data.split()))i = 0return dfs(-inf, inf)
Java版:
public class Codec {private int i;private List<String> nums;private final int inf = 1 << 30;// Encodes a tree to a single string.public String serialize(TreeNode root) {nums = new ArrayList<>();dfs(root);return String.join(" ", nums);}// Decodes your encoded data to tree.public TreeNode deserialize(String data) {if (data == null || "".equals(data)) {return null;}i = 0;nums = Arrays.asList(data.split(" "));return dfs(-inf, inf);}private void dfs(TreeNode root) {if (root == null) {return;}nums.add(String.valueOf(root.val));dfs(root.left);dfs(root.right);}private TreeNode dfs(int mi, int mx) {if (i == nums.size()) {return null;}int x = Integer.parseInt(nums.get(i));if (x < mi || x > mx) {return null;}TreeNode root = new TreeNode(x);++i;root.left = dfs(mi, x);root.right = dfs(x, mx);return root;}
}