上岸核心算法题
  • Catalog
  • 基础题
  • 核心算法200题
    • Sort Algorithms
      • MergeSort
      • Merge Two Sorted Array
      • QuickSort
      • Sort Integers II
      • Partition Array
      • N Car Fleet
      • Reverse Pairs
      • Sort Colors
      • Sort Colors II
      • Subarray Sum closest
      • Merge k Sorted Lists
      • Sort List
    • Binary Search
      • Last Position of Target
      • Positive Product
      • Guess Number Higher or Lower
      • Find Minimum in Rotated Sorted Array
      • Find Minimum in Rotated Sorted Array II
      • Kth Smallest Element in a Sorted Matrix
      • Search a 2D Matrix
      • Maximum Number in Mountain Sequence
      • Find K Closest Elements
      • Search in a Big Sorted Array
      • Fast Power
      • Find Peak Element
      • First Bad Version
      • Search in Rotated Sorted Array
      • add two numbers II
    • LinkedList
      • Reverse Linked List
      • Remove Duplicates from Sorted List
      • Remove Duplicates from Sorted List
      • Merge Two Sorted List
      • Intersection of Two Linked Lists
      • Add Two Numbers
    • List & Queue & Stack
      • Min Stack
      • Evaluate Reverse Polish Notation
      • Convert Expression to Reverse Polish Notation
    • Hashmap & Heap
      • Kth Largest Element in an Array
      • Missing Number
      • Ugly Number II
      • Implement Queue by Two Stack
      • Merge K Sorted Lists
      • Top k Largest Numbers
      • K Closest Points
      • Insert Delete GetRandom O(1)
      • First Unique Character in a String
      • Implement Stack by Two Queues
      • Moving Average from Data Stream
    • Two Pointers
      • Remove duplicates from adjacent/sorted array
      • Reverse String
      • Reverse String II
      • Reverse Words in a String
      • String shift/rotate
      • Reverse Words in a String III
      • Implement strStr()
      • Palindrome Number
      • Valid Palindrome
      • Valid Anagram
      • Kth Largest Element
      • Partition Array
      • 3Sum
      • Sort Colors II
      • Two Sum II - Input array is sorted
      • Sort Integers II
      • Remove Duplicate Numbers in Array
      • Move Zeroes
      • Two Sum III - Data structure design
      • Middle of Linked List
    • BIT Operation & Math
      • Single Number
    • Data Structure
      • First Unique Number in Data Stream
      • Sliding Window
      • Animal Shelter
      • Linked List Cycle II
      • Convert Expression to Reverse Polish Notation
      • Expression Tree Build
    • Binary Tree Divide & Conquer
      • Binary Search Tree Iterator
      • Binary Tree Preorder Traversal
      • Binary Tree Inorder Traversal
      • Symmetric Tree
      • Invert Binary Tree
      • Search Range in Binary Search Tree
      • Largest BST Subtree
      • Lowest Common Ancestor of a Binary Search Tree
      • Lowest Common Ancestor of a Binary Tree
      • BST Node Distance
      • Maximum Width if Binary Tree
      • Construct Binary Tree from Preorder and Inorder Traversal
      • Maximum Depth of Binary Tree
      • Closest Binary Search Tree Value
      • Closest Binary Search Tree Value II
      • Validate Binary Search Tree
      • Lowest Common Ancestor III
      • Kth Smallest Element in a BST
      • Balanced Binary Tree
      • Flatten Binary Tree to Linked List
      • Binary Tree Paths
      • Minimum Subtree
      • Vertical Order Traversal of a Binary Tree
    • BFS
      • Binary Tree
        • Check full binary tree
        • Serialize and Deserialize Binary Tree
        • Graph Valid Tree
        • Check Completeness of a Binary Tree
        • Binary Tree Zigzag Level Order Traversal
        • Binary Tree Level Order Traversal
      • Graph
        • Word Ladder
        • Connected Component in Undirected Graph
        • Open the Lock
        • Clone Graph
        • Search Graph Nodes
        • Course Schedule II
        • Course Schedule
        • Topological Sorting
        • Binary Tree Maximum Path Sum II
        • Shortest Distance from All Buildings
        • Shortest Path in Undirected Graph
        • 八数码问题 Sliding Puzzle II
        • Pacific Atlantic Water Flow
      • Matrix
        • Sequence Reconstruction
        • Knight Shortest Path
        • Knight Shortest Path II
        • Number of Islands
        • Walls and Gates
        • Surrounded Regions
        • Zombie in Matrix
        • Build Post Office II
    • DFS
      • 组合型DFS
        • Letter Combinations of a Phone Number
        • Palindrome Partitioning
        • Split String
        • Generate Parentheses
        • k Sum II
        • Combination Sum IV
        • Combination Sum III
        • Combination Sum II
        • Combination Sum
        • Subsets II
        • Subsets
      • 排列型DFS
        • Permutations
        • Permutations II
        • N-Queens
        • Robot Room Cleaner
      • 剪枝优化
        • Word Pattern II
        • Word Ladder II
    • Memorization search & Dynamic Programming
      • Regular Expression Matching
      • Wildcard Matching
      • Word Break II
      • Word Break
      • Triangle
      • Word Break III
    • Basic Dynamic Programming & Coordinate Dynamic Programming
      • Backpack Problem
        • Backpack
        • Backpack V
        • Backpack II
        • Combination Sum IV (Backpack VI
        • Decode Ways
        • Decode Ways II
      • Coordinate Dynamic Programming
        • Sparse Matrix Multiplication
        • Maximum Submatrix
        • Knight Shortest Path
        • Unique Paths II
        • Unique Paths
        • Minimum Path Sum
        • knight Shortest Path II
        • Distinct Subsequences
        • Paint House
      • Sequential Dynamic Programmin
        • Triangle
        • Longest Increasing Subsequence
        • Number of Longest Increasing Subsequenc
        • Jump Game
        • Jump Game II
        • Best Time to buy and sell
        • Best Time to buy and sell II
      • Median of two Sorted Arrays
      • Median of K Sorted Arrays
      • Merge K Sorted Arrays
      • Merge K Sorted Interval Lists
      • Range Sum Query - Mutable
      • Maximum Subarray
      • Merge Sorted Array
      • Subarray Sum
      • Intersection of Two Arrays
      • Merge Two Sorted Interval Lists
      • Russian Doll Envelopes
      • Largest Divisible Subset
      • Climbing Stairs
    • Other kinds of Problems
      • LRU
      • Longest Palindromic Substring
      • Valid Palindrome
      • Implement strStr()
      • Longest Palindrome
  • 进阶算法200题
由 GitBook 提供支持
在本页

这有帮助吗?

  1. 核心算法200题
  2. BFS
  3. Binary Tree

Serialize and Deserialize Binary Tree

  • 推荐方法

public class Seri {

	String result="";
	int id=0;
	private int serialWork(TreeNode root){
		if (root==null) return -1;
		id++;
		int nowId=id;
		int leftId=serialWork(root.left);
		int rightId=serialWork(root.right);
		result+=root.val+","+nowId+","+leftId+","+rightId+";";
		return nowId;
	}


	public String serialize(TreeNode root) {
		// write your code here
		int rootId=serialWork(root);
		return result;
	}

	public TreeNode deserialize(String data) {
		// write your code here
		String[] nodes=data.split(";");
		HashMap<Integer,TreeNode> nodeHashMap=new HashMap<Integer, TreeNode>();
		for (int i=0;i<nodes.length;i++){
			String[] datas=nodes[i].split(",");
			if (datas.length!=4) continue;
			if (!nodeHashMap.containsKey(Integer.parseInt(datas[1]))) {
				TreeNode node = new TreeNode(Integer.parseInt(datas[0]));
				nodeHashMap.put(Integer.parseInt(datas[1]), node);
			}
			else{
				nodeHashMap.get(Integer.parseInt(datas[1])).val=Integer.parseInt(datas[0]);
			}
			if (!nodeHashMap.containsKey(Integer.parseInt(datas[2])) && Integer.parseInt(datas[2])!=-1){
				nodeHashMap.put(Integer.parseInt(datas[2]),new TreeNode(-1));
			}
			if (!nodeHashMap.containsKey(Integer.parseInt(datas[3])) && Integer.parseInt(datas[3])!=-1){
				nodeHashMap.put(Integer.parseInt(datas[3]),new TreeNode(-1));
			}
			nodeHashMap.get(Integer.parseInt(datas[1])).left=nodeHashMap.get(Integer.parseInt(datas[2]));
			nodeHashMap.get(Integer.parseInt(datas[1])).right=nodeHashMap.get(Integer.parseInt(datas[3]));
		}

		return nodeHashMap.get(1);
	}
}
  • 其他方法

public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node == null) {
                sb.append("N");
            } else {
                sb.append(node.val);
                queue.offer(node.left);
                queue.offer(node.right);
            }
            sb.append("#");
        }
        sb.setLength(sb.length() - 1);
        // System.out.println(sb);
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] strs = data.split("#");
        if (strs.length == 1 && "N".equals(strs[0])) {
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(strs[0]));
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        int i = 1;
        while (i < strs.length) {
            TreeNode node = queue.poll();
            if (!"N".equals(strs[i])) {
                node.left = new TreeNode(Integer.parseInt(strs[i]));
                queue.offer(node.left);
            }
            i++;
            if (!"N".equals(strs[i])) {
                node.right = new TreeNode(Integer.parseInt(strs[i]));
                queue.offer(node.right);
            }
            i++;
        }
        return root;
    }
}
from collections import deque
def serialize(self, root):
    dq = deque([root])
    ans = []
    while dq:
        node = dq.popleft()
        if node:
            ans.append(str(node.val))
            dq.append(node.left)
            dq.append(node.right)
        else:
            ans.append('')
    while ans and not ans[-1]:
        ans.pop()
    return ','.join(ans)

def deserialize(self, data):
    if not data:
        return None
    nodes = map(lambda s: None if not s else TreeNode(int(s)), data.split(','))
    nodes.reverse()
    root = nodes.pop()
    dq = deque([root])
    while nodes:
        node = dq.popleft()
        node.left = nodes.pop()
        if node.left:
            dq.append(node.left)
        if not nodes:
            break
        node.right = nodes.pop()
        if node.right:
            dq.append(node.right)
    return root
上一页Check full binary tree下一页Graph Valid Tree

最后更新于5年前

这有帮助吗?