Question
449. 序列化和反序列化二叉搜索树
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/serialize-and-deserialize-bst/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Ideas
1、Answer( Java ) - 二叉搜索树(BST)后序遍历
解法思路:二叉搜索树(BST)后序遍历
👍后序遍历得到的数组中,根结点的值位于数组末尾,左子树的节点均小于根节点的值,右子树的节点均大于根节点的值,可以根据这些性质设计 递归函数 恢复二叉搜索树。 ??注意事项 : 压栈顺序是 左右根 ,出栈顺序就是 根右左
Code
public class Codec {
public String serialize(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
postOrderSearch(root, list);
String res = list.toString();
return res.substring(1, res.length() - 1);
}
public TreeNode deserialize(String data) {
if (data.isEmpty()) {
return null;
}
String[] strings = data.split(", ");
ArrayDeque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < strings.length; i++) {
stack.push(Integer.parseInt(strings[i]));
}
return reConstruct(Integer.MIN_VALUE, Integer.MAX_VALUE, stack);
}
private void postOrderSearch(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
postOrderSearch(root.left, list);
postOrderSearch(root.right, list);
list.add(root.val);
}
private TreeNode reConstruct(int lower, int upper, ArrayDeque<Integer> stack) {
if (stack.isEmpty() || stack.peek() < lower || stack.peek() > upper) {
return null;
}
int val = stack.pop();
TreeNode root = new TreeNode(val);
root.right = reConstruct(val, upper, stack);
root.left = reConstruct(lower, val, stack);
return root;
}
}
https://leetcode.cn/problems/serialize-and-deserialize-bst/solution/xu-lie-hua-he-fan-xu-lie-hua-er-cha-sou-5m9r4/
https://leetcode.cn/problems/serialize-and-deserialize-bst/solution/by-fuxuemingzhu-6vdj/
|