Common algorithms of binary tree

Keywords: Algorithm Binary tree

1. Traversal of binary tree

1.1 preorder traversal
Middle - > left - > right

public static void preOrderRecur(Node head){
	if(head == null){
		return;
	}
	//Printing at the beginning is the first order traversal, printing at the middle position is the middle order traversal, and printing at the end is the second order traversal.
	System.out.print(head.value+" ");
	preOrderRecur(head.left);
	preOderRecur(head.right);
}

1.2 middle order traversal
Left - > Middle - > right

public static void inOrderRecur(Node head){
 if(head == null){
  return;
 }
  inOrderRecur(head.left);
 //Printing at the beginning is the first order traversal, printing at the middle position is the middle order traversal, and printing at the end is the second order traversal.
 System.out.print(head.value+" ");
 inOderRecur(head.right);
}

1.3 post order traversal
Left - > right - > Center

public static void posOrderRecur(Node head){
 if(head == null){
  return;
 }
 posOrderRecur(head.left);
 posOderRecur(head.right);
 //Printing at the beginning is the first order traversal, printing at the middle position is the middle order traversal, and printing at the end is the second order traversal.
 System.out.print(head.value+" ");
 }

2. Judge whether a binary tree is a balanced binary tree (AVL)

It is an empty tree or the absolute value of the height difference between its left and right subtrees does not exceed 1, and both the left and right subtrees are a balanced binary tree.
Idea 1: starting from the root node, calculate the height of the left and right subtrees of the root. If the height difference between the left and right subtrees of the root is greater than 1, return FALSE. Otherwise, recursively judge whether the left and right subtrees of the root meet the conditions.

public boolean IsBalanced_Solution(TreeNode root) {         
         if(root==null)
             return true;
//Returns TRUE if the tree is null. Otherwise, judge whether the absolute value of the height difference between the left and right subtrees of the root is greater than 1. If greater than 1, return false.
// Otherwise, judge whether the left and right children of the tree are balanced binary trees. When both are balanced binary trees, return TRUE, otherwise return false
         else if(Math.abs(TreeDepth(root.left)-TreeDepth(root.right))>1)
             return false;
         else return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
 
        }
        //Find the depth of the tree.
     public int TreeDepth(TreeNode root)
     {
         if(root==null)
             return 0;
             //If the tree is null, return 0, otherwise return the maximum value of left and right children + 1.
         return Math.max(TreeDepth(root.left), TreeDepth(root.right))+1;

Idea 2: in the above method, the height of subtree is calculated repeatedly. You can use post order traversal from bottom to top. If any of the subtrees does not meet the conditions, it returns false, otherwise it returns true. In this way, the height of each node will be calculated only once.

public class IsBalancedTree {
    boolean isBalance=true;
    public boolean IsBalanced_Solution(TreeNode root) {         
         TreeDepth1(root);
         return isBalance;
        //isBalance is assigned in TreeDepth1(root).
        }
    public int TreeDepth1(TreeNode root)
     {
         if(root==null)
             return 0;
         int left=TreeDepth1(root.left);
         //Left subtree height
         int right=TreeDepth1(root.right);
         //Right subtree height
         if(Math.abs(left-right)>1)
         {
             isBalance=false;
             //As long as the absolute value of the height of the left and right subtrees of a subtree is greater than 1, isBalance = false
         }
         return Math.max(left, right)+1;

3. Determine whether a tree is a search binary tree

For any node, the left subtree is smaller and the right subtree is larger.
**Idea: * * the search binary tree is in the order from small to large in the middle order traversal (left, middle and right).
We can use a pre variable to save the precursor node and initialize pre to a value as small as possible.
Conversely, if there is a current node smaller than its predecessor, then the tree is not a binary search tree.

//An improved algorithm for judging whether a given binary tree is a BST tree
    boolean isBSTOfBetter(BinaryTreeNode<T> root,int pre) {
    	if(root == null)
    		return true;
    	//If a left subtree is not a BST tree, false is returned
    	if(!isBSTOfBetter(root.getLeft(), pre))
    		return false;
    	//If the current node is smaller than the predecessor node, false is returned
    	if((int)root.getData() < pre)
    		return false;
    	//Update precursor node
    	pre = (int) root.getData();
    	//If a right subtree is not a BST tree, false is returned
    	if(!isBSTOfBetter(root.getRight(), pre))
    		return false;
    	return true;
    }

4. Judge whether a tree is a complete binary tree

Complete binary tree: it is agreed to number each node in the full binary tree from 1 to n from the root, from top to bottom, from left to right.
**Idea: * * according to the definition of complete binary tree, complete binary tree is traversed from top to bottom and from left to right. The following two requirements should be met:
● if there is no left child at a node, there must be no right child
● if a node lacks left or right children, all its successors must have no children
If any of the above conditions is not satisfied, it is not a complete binary tree.

public static boolean isCBT(Node head){
	if(head == null){
		return true;
	}
	Queue<Node> queue = new LinkedList<Node>();
	//Determine when the leaf node phase is turned on
	boolean leaf = false;
	Node l = null;
	Node r = null;
	queue.offer(head);
	while(!queue.isEmpty()){
		head = queue.poll();
		l = head.left;
		r = head.right;
		//If the left node is empty, the right node is not empty, or the leaf node stage is enabled, then the left and right nodes still have child nodes, then it is false
		if((leaf &&(l != null || r != null)) || (l == null && r!= null)){
			return false;
		}
		if(l != null){
			queue.offer(l);
		}
		if(r != null){
			queue.offer(r);
		}else{
			leaf = true;
		}
	}
	return true;
	}

5. trie tree (prefix tree / dictionary tree)

Basic properties
1. The root node does not contain characters. Except for the root node, each node contains only one character.
2. From the root node to a node, the characters passing through the path are connected to the corresponding string of the node.
3. All child nodes of each node contain different strings.

(1) String retrieval
Save the relevant information of some known strings (dictionaries) to the trie tree in advance to find out whether other unknown strings have appeared or their frequency.
(2) Text prediction, autocomplete, see also, spell check
(3) Word frequency statistics

Posted by walter8111 on Tue, 30 Nov 2021 06:58:40 -0800