Summary of Tree Topics on Sword Finger offer

Keywords: network less Python github

Tree problems can usually be solved by recursion. The essence of recursion process is stack, so recursion can also be solved by cyclic stacking (or queue) in theory.

On Recursion

Recursion is very easy to confuse people's thinking. It's very useful to see a kind of thinking on the internet, that is, to assume that the sub-problems have been perfectly dealt with. You only need to think about the way to deal with the final problem, and the way to deal with the sub-problems is the same as the way to deal with the final problem, so the thinking will be much clearer.
The following code examples are all python versions

Topic 1: Printing binary trees from top to bottom
Title Description:

Each node of the binary tree is printed from top to bottom, and the same layer node is printed from left to right.

Algorithmic ideas:

Obviously, it can be solved by hierarchical traversal, that is, breadth traversal, printing from top to bottom, that is, after each layer has been printed, it is necessary to continue printing the child nodes in the order of the parent nodes.
It accords with the characteristics of queue FIFO, so it can be solved by queue + loop judgment.
That is to say, by means of queue, the root node is added to the queue, and every time it traverses to a node, the node is removed from the queue and the left and right nodes of the node are added to the queue, and the process is repeated until the queue is empty.

Keyword: Queue loops

The code is as follows

# -*- coding:utf-8 -*-
class TreeNode:
	def __init__(self, x):
		self.val = x
		self.left = None
		self.right = None

class Solution:
	# Returns a list of values for each node from top to bottom, for example: [1, 2, 3]
	def PrintFromTopToBottom(self, root):
		if root is None:
			return []
		tempnode = []
		tempnode.append(root)
		valres = []
		while (len(tempnode) > 0):
			node = tempnode.pop(0)
			valres.append(node.val)
			if node.left is not None:
				tempnode.append(node.left)
			if node.right is not None:
				tempnode.append(node.right)
		return valres

Topic 2: Mirror image of binary tree
Title Description:

Operate a given binary tree and transform it into a mirror image of the source binary tree.
As follows:

Algorithmic ideas:

From the title, we can see that the mirror image of the binary tree can be seen as a process of swapping left and right sub-nodes, as follows:

Therefore, we can complete the image of the binary tree by exchanging the left and right sub-nodes of the current node on the basis of the pre-order traversal (the order is root sub-tree - > left sub-tree - > right sub-tree).
The code is as follows

# -*- coding:utf-8 -*-
'''
	//Mirror image of tree
	//Ideas: Recursive exchange of left and right nodes
'''
class TreeNode:
	def __init__(self, x):
		self.val = x
		self.left = None
		self.right = None

class Solution:
	# Returns the root node of the mirror tree
	def Mirror(self, root):
		# write code here
		if root is None:
			return root
		if root.left is None and root.right is None:
			return root
		tempNode = root.left
		root.left = root.right
		root.right = tempNode
		self.Mirror(root.left)
		self.Mirror(root.right)

Key words: recursive preamble traversal
Topic 3: Postorder traversal sequence of binary search tree
Title Description:

Enter an integer array to determine whether the array is the result of a post-order traversal of a binary search tree. If so, return True or False. Assume that any two numbers of the input array are different from each other.

Algorithmic ideas:

Binary search tree:

It refers to an empty tree or a binary tree with the following properties:

If the left subtree of any node is not empty, the value of all nodes in the left subtree is less than the value of its root node.
If the right subtree of any node is not empty, the values of all nodes in the right subtree are larger than those of its root node.
The left and right subtrees of any node are also binary search trees.
There are no nodes with equal keys.

Post-order traversal order: left subtree - > right subtree - > root node

1) Recursive method
According to the characteristics of binary search tree, every non-empty node of the left subtree is not larger than the root node, and every non-empty node of the right subtree is not smaller than the root node. The Title stipulates that every node in the sequence is not repeated, so we can determine the title. In the test cases given, each node of the left subtree is bound to be smaller than the root node, and each node of the right subtree is bound to be larger than the root node.
So looking from left to right, finding the first value larger than the root node indicates that the element to the left is the left subtree, and the element to the right is the right subtree before the last node.
If any element of the left subtree is larger than the root node, or any element of the right subtree is smaller than the root node, the sequence is not a binary search tree traversal sequence.
This method is used for recursive judgment.


The last element 8 in the graph is the root node, and element 9 is the first value larger than the root node in the left-to-right sequence, the left subtree in the 9-to-left sequence, and the right subtree in the 9-to-right sequence before the last element 8.
Observation shows that if the binary search tree is matched, the sequence elements of the right subtree are larger than the root node.
Left and right subsequences can be judged recursively by this method.
The code is as follows

# -*- coding:utf-8 -*-
class Solution:
	def VerifySquenceOfBST(self, sequence):
		# write code here
		if sequence is None or len(sequence) == 0:
			return False
		return self.VerifyBST(sequence)

	def VerifyBST(self,verifys):
		if len(verifys) <= 1:  # Only the root node remains
			return True
		root = verifys[-1]
		temps = verifys[:-1]
		lefts = []
		rights = []
		for i in range(len(temps)):
			if temps[i] > root:
				lefts = temps[0:i]
				if i <= len(temps) - 1:
					rights = temps[i:-1]
				break
		else:
			lefts = temps
		for v in rights:
			if v < root:
				return False
		return self.VerifyBST(lefts) and self.VerifyBST(rights)

2) Non-recursive method (as seen on Niuke Network)
The general idea is to use the current node A as the root node and traverse the value of the sequence ahead of node A according to the post-order traversal. If the current sequence element value is less than the value of node A, and the former sequence element value is larger than the value of node A, it is not a binary search tree.

Reference link Cattle and Passenger Network

Picture Invasion and Deletion

Key words: characteristics of recursive binary search tree
Topic 4: Path of Neutralizing a Value in a Binary Tree
Title Description:

Input the root node and an integer of a binary tree, print out all paths with the sum of the node values in the binary tree as the input integer. A path is defined as a path from the root node of a tree down to the node through which the leaf node passes.

Algorithmic ideas:

The path refers to the node from the root node of a tree to the leaf node, so the question is actually to find the sum of all the nodes on the path from the root node to a leaf node and whether it is the required value in the title.
Because the calculation starts from the root node, it can be seen as calculating the path sum on the basis of the tree's pre-order traversal. Because the title requires printing the path, the current node needs to be recorded each time traversing the node. When reaching the leaf node, it needs to judge whether the path meets the requirements. When the recursion falls back to the previous node, it needs to record the current node. The current node, the last node of the path, needs to be removed from the path, and the recorded path can be stacked.
Examples:

The root node joins the stack to the leaf node, and the stack joins the sequence of 10,5,4.
10+5+4 is not equal to 22 and does not record paths.
Eject 4, return to parent node 5, stack sequence 10,5;
Right leaf node 7 is stacked, stack sequence 10, 5, 7, equal to 22, recording path;
Eject 7, return 5;
Eject 5, return to 10;
Leaf node 12 is stacked, stack sequence 10,12 equals 22, recording path;
So the qualified paths are [10, 5, 7] and [10, 12].

# -*- coding:utf-8 -*-
"""
//The path of neutralizing a certain value in a binary tree
"""
class TreeNode:
	def __init__(self, x):
		self.val = x
		self.left = None
		self.right = None
class Solution:
	# Returns a two-dimensional list, each of which represents the path found
	def FindPath(self, root, expectNumber):
		return self.RealFindPath(root, 0, expectNumber, [], [])

	def RealFindPath(self, root, sum, expectNumber, path, allpath):
		if root is None:
			return allpath
		sum += root.val
		path.append(root.val)
		if root.left is None and root.right is None:
			if sum == expectNumber:
				allpath.append(path[:])
		if root.left:
			self.RealFindPath(root.left, sum, expectNumber, path, allpath)
		if root.right:
			self.RealFindPath(root.right, sum, expectNumber, path, allpath)
		# Pop up the current element before going back to the previous node
		if len(path) > 0:
			num = path.pop()  # Pop-up End Element
			sum = sum - num
		return allpath
Key words: recursive stack
Topic 5: Symmetric Binary Trees
Title Description:

Please implement a function to determine whether a binary tree is symmetrical. Note that if a binary tree has the same mirror image as the binary tree, it is defined as symmetric.

Algorithmic ideas:

Recursive method:
As shown in the following figure, from the symmetrical binary tree observation, the left node (rectangle 1) of the left child node (6) of the same parent node and the right node (rectangle 1) of the right child node (6) of the right child node (rectangle 1) are not equal if one is empty and the other is not empty, or the right node (circle 3) of the left child node (6) of the same parent node and the right node (circle 3) of the right child node (6) of the same parent node are not equal. If the left node (circle 3) of the right sub-node (6) is not equal (one is empty and the other is not empty, it is also not equal), then the binary tree is not symmetric.

# -*- coding:utf-8 -*-
class TreeNode:
	def __init__(self, x):
		self.val = x
		self.left = None
		self.right = None
	
class Solution:
	def isSymmetrical(self, pRoot):
		if pRoot is None:
			return True
		return self.IsRealSymmetrical(pRoot.left, pRoot.right)

	def IsRealSymmetrical(self, Lroot, Rroot):
		if (Lroot and Rroot is None) or (Rroot and Lroot is None):
			return False
		if Lroot is None and Rroot is None:
			return True
		if Lroot.val != Rroot.val:
			return False
		return self.IsRealSymmetrical(Lroot.left, Rroot.right) and self.IsRealSymmetrical(Lroot.right, Rroot.left)

Key words: recursive non-recursive
Title 6: Reconstructing Binary Trees
Title Description:

Enter the results of the pre-order and middle-order traversals of a binary tree, and rebuild the binary tree. It is assumed that the results of the input preamble traversal and the intermediate order traversal do not contain duplicate numbers. For example, the binary tree is reconstructed and returned if the pre-order traversal sequence {1,2,4,7,3,5,6,8} and the middle-order traversal sequence {4,7,2,1,5,3,8,6} are input.

Algorithmic ideas:

The binary tree can be obtained from the preface sequence and the intermediate sequence. From the traversal process of the preceding sequence, we can know that the first element of the preceding sequence is the root node, and the root node is found in the middle sequence. The root node in the sequence is left subtree, and the root node is right subtree. According to this method, the binary tree can be reconstructed recursively. The essence of recursion is stack (FIFO), so the final recursive return node is the root node.

Key words: recursion

==============================
Find a fun project~
https://github.com/Wscats/piano

Posted by nick2005 on Fri, 23 Aug 2019 00:27:28 -0700