Binary Tree

"""Binary Search Tree

Included:
	- Insert
    - Find data/ minimum/ maximum
    - Size
    - Height
    - Traversals (Inorder, preorder, postorder)
    - Test Code for it
    
Not included:
	- Delete
    - Display (as 2D BST)
	and others...
"""

class Node: # Node
    def __init__(self, data, start=None):
        self.data = data
        self.left = self.right = start

class BinarySearchTree:
    def __init__(self):
        self.root = None

    # Insert a node
    def put(self, data):
        if self.root is None: # BST empty
            self.root = Node(data)
        else:
            curr = self.root # initialise curr pointer
            while curr:
                if data < curr.data: # data put at left
                    if curr.left:
                        curr = curr.left
                    else: # no left child
                        curr.left = Node(data)
                        break
                else: # data put at right
                    if curr.right:
                        curr = curr.right
                    else:  # no right child
                        curr.right = Node(data)
                        break   
                        
    def find(self, data):
        curr = self.root   # start from root
        while curr:
            if data < curr.data:  # data at left
                curr = curr.left
            elif data > curr.data:    # data at right
                curr = curr.right
            else:
                return True # found
        return False
    
    def min_of(self):
        curr = self.root # start from root
        while curr.left:
            curr = curr.left # keep going left
        return curr.data
        
    def max_of(self):
        curr = self.root # start from root
        while curr.right:
            curr = curr.right # keep going right
        return curr.data
    
    def size(self):
        def go(node): # helper
            if node:
                return 1 + go(node.left) + go(node.right)
            return 0
        return go(self.root)   
    
    def height(self):
        def go(node): # helper
            if node:
                return 1 + max(go(node.left), go(node.right))
            return -1 # it has -1 if empty
        return go(self.root)

        
    # In_order
    def in_order(self):
        lst = [] # results
        def go(node): # helper
            nonlocal lst
            if node: # If node exists
                go(node.left) # left
                lst.append(node.data) # Node
                go(node.right) # Right
        go(self.root)
        return lst
    
    # Pre_order
    def pre_order(self):
        lst = [] # results
        def go(node): # helper
            nonlocal lst
            if node: # If node exists
                lst.append(node.data) # Node
                go(node.left) # left
                go(node.right) # Right
        go(self.root)
        return lst
    
    # Post_order
    def post_order(self):
        lst = [] # results
        def go(node): # helper
            nonlocal lst
            if node: # If node exists
                go(node.left) # left
                go(node.right) # Right
                lst.append(node.data) # Node
        go(self.root)
        return lst

# Test
from random import randint, sample
def BST_tester(BST):
    r = randint(5, 10)
    lst = [randint(10, 100) for _ in range(r)]
    print(f"List: {lst}", 
          f"Sorted: {sorted(lst)}",
          sep = "\n", end = "\n\n")
    
    B = BST()
    for item in lst:
        B.put(item)
    lst.sort()
    print("AFTER INSERTION:",
          f"Size: {B.size()} | {B.size() == len(lst)}",
          f"Height: {B.height()} | I can't code the display for this",
          f"Min: {B.min_()} | {B.min_() == min(lst)}",
          f"Max: {B.max_()} | {B.max_() == max(lst)}",
          sep = "\n", end = "\n\n")
    
    items = sample(lst, 5) + [randint(10, 100) for _ in range(5)] # 5 confirm in list, 5 might be in list
    found = [B.find(_) for _ in items]
    zipped = list(zip(items, found))
    inlst, notinlst = zipped[:5], zipped[5:] 
    print(f"Sampled from lst: {inlst} | All True: {all(found[:5])}",
          f"Random: {notinlst}",
          sep = "\n", end = "\n\n")
    
    print(f"Inord: {B.in_ord()} | Correct Insertion: {lst == B.in_ord()}",
          f"Preord: {B.pre_ord()}",
          f"Postord: {B.post_ord()}",
          sep = "\n")
BST_tester(BST)

binary tree

// invert binary tree : (right node >> left node && left node >> right node )
 const invertTree =(root)=>{
if(root===null) return root;
  let queue =[root] ; 
  while(queue.length>0){

let node =queue.shift() ; 
if(node !=null){
  let hold = node.left ;
  node.left =node.right; 
  node.right =hold ; 
  if(node.left) queue.push(node.left) ;

  if(node.right) queue.push(node.right) ;
}
  }
  
return root;

 }

binary tree

class Node:
    def __init__(self,key):
        self.left = None
        self.right = None
        self.val = key
 
root = Node(1)
root.left      = Node(2);
root.right     = Node(3);
root.left.left  = Node(4);

binary tree

contains(value) {
    let current = this.root;
    while (current) {
      if (value < current.value) {
        current = current.left;
      } else if (value > current.value) {
        current = current.right;
      } else {
        return true;
      }
    }
    return false;
  }
}
//if you find this answer is useful ,
//upvote ⇑⇑ , so can the others benefit also . @mohammad alshraideh ( ͡~ ͜ʖ ͡°)

binary tree

 Add(value) {
    let current = this.root;
    if (!current) {
      this.root = new Node(value);
    }
    else {
      while (current) {
        if (value < current.value) {
          if (!current.left) {
            current.left = new Node(value);
            break;
          }
          current = current.left;
        }
        else {
          if (!current.right) {
            current.right = new Node(value);
            break;
          }
          current = current.right;
        }
      }
    }
  }

//if you find this answer is useful ,
//upvote ⇑⇑ , so can the others benefit also . @mohammad alshraideh ( ͡~ ͜ʖ ͡°)

Binary tree

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStructure
{
    namespace Tree
    {
        internal class BinaryTree
        {
            private Node root;
            public void Insert(int data)
            {
                var node = new Node(data);
                if (root == null)
                {
                    root = node;
                    return;
                }

                var current = root;

                while (true)
                {
                    if (current.data > data)
                    {
                        if (current.leftChild == null)
                        {
                            current.leftChild = node;
                            break;
                        }
                        current = current.leftChild;
                    }
                    else if (current.data < data)
                    {
                        if (current.rightChild == null)
                        {
                            current.rightChild = node;
                            break;
                        }
                        current = current.rightChild;
                    }
                }
            }
            public void InOrder()
            {
                InOrder(root);
            }
            public void PreOrder()
            {
                InOrder(root);
            }
            public void PostOrder()
            {
                InOrder(root);
            }
            private void InOrder(Node node)
            {
                if (node == null)
                    return;
                InOrder(node.leftChild);
                Console.Write(node.data);
                InOrder(node.rightChild);
            }
            private void PreOrder(Node node)
            {
                if (node == null)
                    return;
                Console.Write(node.data);
                PreOrder(node.leftChild);
                PreOrder(node.rightChild);
            }
            private void PostOrder(Node node)
            {
                if (node == null)
                    return;
                PostOrder(node.leftChild);
                PostOrder(node.rightChild);
                Console.Write(node.data);
            }

            public int Height()
            {
                return Height(root);
            }
            private int Height(Node node)
            {
                if (node == null)
                {
                    return -1;
                }
                if (IsLeaf(node))
                {
                    return 0;
                }
                return 1 + Math.Max(Height(node.leftChild), Height(node.rightChild));
            }
            private bool IsLeaf(Node node)
            {
                if (node.leftChild == null && node.rightChild == null)
                {
                    return true;
                }
                return false;
            }

            public bool IsEqual(Node first, Node second)
            {
                if (first == null && second == null)
                    return true;
                if (first != null && second != null)
                {
                    return first.data == second.data &&
                        IsEqual(first.rightChild, second.rightChild) &&
                        IsEqual(first.leftChild, second.leftChild);
                }
                return false;
            }
        }
        public class Node
        {
            public int data;
            public Node leftChild;
            public Node rightChild;
            public Node(int data)
            {
                this.data = data;
            }
        }
    }
}

binary tree

#include <iostream>
#include <queue>
using namespace std;
struct Node{
   int data;
   struct Node* left, *right;
};
// Function to count the full Nodes in a binary tree
int fullcount(struct Node* node){
   // Check if tree is empty
   if (!node){
      return 0;
   }  
   queue<Node *> myqueue;
   // traverse using level order traversing
   int result = 0;
   myqueue.push(node);
   while (!myqueue.empty()){
      struct Node *temp = myqueue.front();
      myqueue.pop();
      if (temp->left && temp->right){
         result++;
      }
      if (temp->left != NULL){
         myqueue.push(temp->left);
      }
      if (temp->right != NULL){
         myqueue.push(temp->right);
      }
   }
   return result;
}
struct Node* newNode(int data){
   struct Node* node = new Node;
   node->data = data;
   node->left = node->right = NULL;
   return (node);
}
int main(void){
   struct Node *root = newNode(10);
   root->left = newNode(20);
   root->right = newNode(30);
   root->left->left = newNode(40);
   root->left->right = newNode(50);
   root->left->left->right = newNode(60);
   root->left->right->right = newNode(70);
   cout <<"count is: "<<fullcount(root);
   return 0;
}

binary tree

void preorder(node *n) {
    cout << n->value;
    if(n->left!=NULL)
        preorder(n->left);
    if (n->right != NULL)
        preorder(n->right);
}
void inorder(node *n) {
    if (n->left != NULL)
        inorder(n->left);
    cout << n->value;
    if (n->right != NULL)
        inorder(n->right);
}
void postorder(node *n) {
    if (n->left != NULL)
        postorder(n->left);
    if (n->right != NULL)
        postorder(n->right);
    cout << n->value;
}

Binary tree

void preorder(node *n) {
    cout << n->value;
    if(n->left!=NULL)
        preorder(n->left);
    if (n->right != NULL)
        preorder(n->right);
}
void inorder(node *n) {
    if (n->left != NULL)
        inorder(n->left);
    cout << n->value;
    if (n->right != NULL)
        inorder(n->right);
}
void postorder(node *n) {
    if (n->left != NULL)
        postorder(n->left);
    if (n->right != NULL)
        postorder(n->right);
    cout << n->value;
}

binary tree

Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Source: leetcode.com

binary tree

  peek() {
    return this.elements[this.head];
  }


//if you find this answer is useful ,
//upvote ⇑⇑ , so can the others benefit also . @mohammad alshraideh ( ͡~ ͜ʖ ͡°)

binary trees

compare(tree1 ,tree2 ){

let x =tree1.count()
let y =tree2.count()

if(x==y)return true; else return false;
}


//if you find this answer is useful ,
//upvote ⇑⇑ , so can the others benefit also . @mohammad alshraideh ( ͡~ ͜ʖ ͡°)

binary tree

// minimum node in binary tree
const BreadthFirstsearchMin =(root)=>{
let min = Infinity ;
let queue = [root];
while(queue.length){
let current = queue.shift();
if(current.data < min) {
  min=current.data;
}
if(current.left!== null) queue.push(current.left);
if(current.right !==null) queue.push(current.right);
}
return min ;
}

binary tree

// find maixmum node in binary tree 
const Max = (root) => {
  let max = -Infinity;
  let stack = [root];

  while (stack.length) {
    let current = stack.pop();
    if (current.data > max) {
      max = current.data;
    }
    if (current.left !== null) stack.push(current.left);
    if (current.right !== null) stack.push(current.right);
  }

  return max;
};

binary tree

// check if mirror binary tree or not (give two binary trees and you need to find if they are a mirror to each other )
const isMirror =(tree1 ,tree2)=>{
if(tree1 ===null && tree2 ===null) return true ;
if(tree1.data == tree2.data){
  if(isMirror(tree1.left ,tree2.right) && isMirror(tree1.right ,tree2.left)){
    return true 
  }else return false
} else{
  return false
} 
  }

binary tree

#include <bits/stdc++.h>
using namespace std;
  
class Node {
  public:
    int data;
    Node* left;
    Node* right;
  
    // Val is the key or the value that
    // has to be added to the data part
    Node(int val)
    {
        data = val;
  
        // Left and right child for node
        // will be initialized to null
        left = NULL;
        right = NULL;
    }
};
  
int main()
{
  
    /*create root*/
    Node* root = new Node(1);
    /* following is the tree after above statement
  
             1
            / \
        NULL   NULL
    */
  
    root->left = new Node(2);
    root->right = new Node(3);
    /* 2 and 3 become left and right children of 1
                  1
                /   \
                2      3
               / \     / \
            NULL NULL NULL NULL
    */
  
    root->left->left = new Node(4);
    /* 4 becomes left child of 2
              1
            /    \
           2      3
          / \     / \
         4 NULL NULL NULL
        / \
      NULL NULL
    */
  
    return 0;
}

C#相关代码片段

stackpanel opacity mask from resources wpf

how to code

c# array isn't working

hydrogen fuels

generate parentheses

random class

reverse array

translator

stack over flow

prime number algorithm

palindrome

palindromes

rigidbody velocity

randomise array

shuffle array

fisher yates shuffle

prime numbers

generate prime numbers

rest api in c#

poisson distribution

ms transform

wetter warendorf

querstring fromat asp.net c#

null objects

skrivetænking

how to close a popup wpf c# on click event

Function delegate

next permutation

CullingGroup

händelsereportage

Delegates in UntiyC#

getcomponent

class combining

tee into file

reverse integer

how long dose it take for formate a currupt USB?

team fortress

card caption

math round to next integer c#

calculator

skrivetækning

remove element

class merging

dadar pincode

ASP.MVC display image from SqlServer

hive survive

c# delegates

wpf onpropertychanged not working

loop through dictionary

get the next letter after specific character in c#

how to make character respawn if touches sprite c#

snake spielen

mental retardation

palindrome number

download file

c# language

static variables

codegrepper

tomatch jest

linkedlist sorting

index sort

multidimensional meaning

Boolean Literals

Working with null values

samsung sam

dsharp emoji from string

print bitmap company logo c sharp

gersener waves

www.elking.net

active form

add rotation

texture matrix

ip address

delete directory

inheritance

uppercase letter

binary tree

assert throw

triangle area

ado stands for