Some algorithms of the binary tree

xiaoxiao2021-03-05  27

(1) Algorithm for seeking the number of binary tree nodules.

TypeDef struct node {charct node * lchild, * rchild;} node; int nodenumber (node ​​* root) {if (root <= null) return (0); Else Return (1 nodenumber (root-> lchild) nodenuber (root-> rchild);} (2) Outputs all leaves of the binary tree.

Void Showleaves (Node * root) {if (root == null) return; if (root-> lchild == null && root-> rchild == null) {Printf ("% C", root-> data); return;} Else if (root-> lchild! = null) Showleaves (root-> lchid); if (root-> rchild! = null) showleaves (root-> rchild);} (3) Ask the binary tree depth algorithm.

INT TREEDEPTH (Node * root) {if (root-> null) return (-1); if (root-> lchild == null && (root-> rchild == null) Return (0); Else Return (TreeDepth -> lchild> Treedepth (root-> rchild)? (1 Treedepth): (1 Treedepth);} (4) Put the left and right bon trees of all nodes in the tree Exchange algorithm.

Void treeswap (node ​​* root) {if (root == null | (root-> lchild == null && root-> rchild == null) return; p = root-> lchild; root-> lchild = root-> rchild; root -> rchild = p; treeswap (root-> lchild); TREESWAP (root-> rchild); (5) Algorithm to traverse binary trees in the order of hierarchy (from left to right).

Void Levorder (T, M) Node * T; INT M; {Node * q [100], * p; int head, tail, i; q [0] = T; Head = 0; tail = 1; while (Head data); for (i = 0; i child [i]! = null) Q [Tail ] = P-> Child [i];}} (6) Copy the binary tree algorithm.

转载请注明原文地址:https://www.9cbs.com/read-35778.html

New Post(0)