Algorithm Learning notes (vi) binary tree and graph traversal-deep search DFS and wide search BFS

Source: Internet
Author: User

Deep search and wide search of graphs

Review the next two tree, the deep search and wide search.

From the graph's traversal. There are two ways to traverse a graph: depth-first traversal (Depth, first search), breadth-priority traversal (breadth-search), its classic application maze, n-Queen, binary tree traversal, and so on. Traversal is to access all the nodes in the graph in some order, in the following order:

    • Depth first (first to go deep), the data structure used is the stack, mainly recursive implementation.
    • Breadth-first (first-come-recent). The data structure used is a queue. is mainly iterative implementation.

For deep search. Because recursion is often convenient to use the system stack, do not need to maintain their own stack. So it's usually easier to implement.

And for the wide search. You need to maintain a queue yourself, and because the queue size is unknown, the physical structure of the underlying storage is linked to storage.

The concept and properties of binary tree

A binary tree is a tree structure with a maximum of two subtrees per node, and is often used to implement a two-fork lookup tree and a two-fork heap.

in graph theory, a binary tree definition is a connected, loop-free graph . And the degree of each vertex is not less than 2. Binary trees and trees have a lot of similarities, but not the special case of trees, there are mainly three points below the main difference:

    1. There is no limit to the maximum number of nodes in a tree, and the maximum number of binary tree nodes is 2.
    2. The nodes of the tree have no left and right points, while the nodes of the binary tree have left and right points.
    3. The number of nodes in a tree is at least 1, and the number of nodes in a binary tree can be 0.
Some related concepts of the tree:
    • Node Degree: The number of sub-trees owned by the node is called the degree of the nodal point. A binary tree is just 0, 1. 23 kinds of situations;
    • Leaf nodes: Nodes with a degree of 0 are called leaf nodes, or terminal nodes;
    • Branching nodes: Nodes with a degree of not 0 are called branch nodes, and the nodes of a tree are branch nodes except for the leaf nodes.
    • Number of nodes: the number of layers of the root node of the specified tree is 1, the number of layers of the remaining nodes equals the number of layers of its parent node plus 1;
    • Depth of tree: the maximum number of nodes in a tree is called the depth of the tree;
    • path, path length. Suppose a string of nodes of a tree n (1), N (2),?..., N (k)? There are, for example, the following relationship: node n (i) is the parent node of N (i+1) (1≤i<k), and N (1), N (2),..., N (k) is called a path from N (1) to n (k).

      The length of the path is k-1;

    • Full two fork tree: In a binary tree, assume that all branch nodes have Saozi right subtree, and all leaf nodes are on the same layer.
    • Completely binary tree: The depth is K. A two-fork tree with N nodes, when and only if each of its nodes corresponds to a node one by one in a full two-fork tree with a depth of K, from 1 to N;
    • Heap is a completely binary tree , often used in sorting algorithm, Dijkstra algorithm, Prim algorithm, etc. are often used heap optimization;
    • AVL Tree: It is the first to invent the self-balancing binary search tree, whose name comes from its inventor, the maximum difference between the height of the two subtrees of any node in the AVL tree is 1, and the lookup, insertion, and deletion are O (LOGN) in the average and worst case;
The important properties of a binary tree:
    • Property 1: There are at most 2i-1 nodes (i≥1) on the first layer of a binary tree;
    • Property 2: The two-fork tree with a depth of K contains at most 2k-1 nodes (k≥1);
    • Property 3: No matter what a binary tree, if it contains n0 a leaf node, N2 degree of 2 nodes, then: N0 = n2+1;
    • Property 4: The depth of the total binary tree with n nodes is log2n+1;
    • Property 5: If the total binary tree containing n nodes is numbered from top to bottom and from left to right (that is, by sequence), 1 to N. A node numbered I in a completely binary tree:
      (1) If i=1, then the node is the root of two fork tree, no parents, otherwise. The node with the number I/2 is the parent knot point;
      (2) if 2i>n. Then the node has no left child. Otherwise, the node with the number 2i is the left child node.
      (3) If 2i+1>n, then the node has no right child node. Otherwise, the node numbered 2i+1 is the right child node;
Small Experiment (C implementation)

Here we first use an array to generate a completely binary tree (chained storage), and then deep search using the pre-sequence traversal, wide search with their own implementation of a queue (chain storage) to do. The figure is as follows:

The code is:
#include <stdio.h> #include <stdlib.h>typedef struct Node {int data;struct node * left;struct node * RIGHT;}  Bitnode, *bitree;typedef bitree qelemtype;   Defines the queue element type typedef struct QNODE {qelemtype data; Store tree node pointer struct qnode *next;}  Qnode, *queueptr; Queue node and node pointer typedef struct LINKQUEUE {queueptr front, rear;} Linkqueue; Pre-and post-queue pointers: Team head. Team Tail/* Initialize queue */int initqueue (Linkqueue *q) {queueptr s = (queueptr) malloc (sizeof (Qnode)), if (!s) return 0; Q->front = s; Q->rear = S;return 1;} /* Queue */int EnQueue (Linkqueue *q, Qelemtype e) {if (E = = NULL) return 0; Queueptr s = (queueptr) malloc (sizeof (Qnode)), if (!s) return 0;s->data = E;s->next = NULL; Q->rear->next = s; Q->rear = S;return 1;} /* Out Team */int DeQueue (linkqueue *q, Qelemtype *e) {if (Q->front = = q->rear) {return 0;}//The first pointer is equal. Queue empty, out of team failure queueptr p;p = q->front->next; The head node does not put data, its successor node as the team head, the team *e = p->data; Q->front->next = p->next; The team first pointer moves back one node if (q->rear = = p) {q->rear = Q->front;}//TailThe pointer is assumed to point to the first node after the head junction, so it points to the team's first pointer. That is, the queue has only one data node in the case free (p); return 1;} /* Create a two-fork tree with array A. The writing technique of recursion is to design the function interface */void createtree (bitree *bt, int a[], int len, int index) {if (Index > Len-1) return; (*BT) = (bitree   ) malloc (sizeof (Bitnode));   Pointer variables initialize memory of the heap area, C with malloc function (*BT)->data = A[index];(*bt)->left = NULL; cannot be omitted, when it is a leaf node, the pointer field is NULL, and is often used as a program inference condition (*BT)->right = null; Createtree (& (*BT)->left), A, Len, 2 * index + 1); Createtree (& (*BT)->right, A, Len, 2 * index + 2);} /* Pre-order Traversal binary tree, which belongs to depth-first traversal DFS */void preordertraverse (Bitree bt) {if (BT = = NULL) return;printf ("%d", bt->data); Operation node Data preordertraverse (Bt->left); Preordertraverse (bt->right);} /* Traversal by layer, that is, breadth-first traversal of BFS */void Bfstraverse (Bitree bt) {linkqueue *q = (Linkqueue *) malloc (sizeof (linkqueue)); Bitree E;initqueue (Q); EnQueue (q, BT), while (q->front! = q->rear) {DeQueue (q, &e);p rintf ("%d", e->data); EnQueue (Q, e->left); EnQueue (Q, e->right);}} int main () {int arr[] = {0, 1, 2, 3, 4, 5, 6}; Bitree Root; Createtree (&root, arr, sizeof (arr)/sizeof (int), 0);p rintf ("Preordertraverse:"); Preordertraverse (Root);p rintf ("\nbfsordertravesre:"); Bfstraverse (root); return 0;} /* program execution such as the following: preordertraverse:0 1 3 4 2 5 6bfsordertravesre:0 1 2 3 4 5 6 * *
"Article Address is: Http://blog.csdn.net/thisinnocence"

Algorithm Learning notes (vi) binary tree and graph traversal-deep search DFS and wide search BFS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.