Inferred binary tree is an unbalanced tree code (C)
This address: Http://blog.csdn.net/caroline_wendy
Title: Enter the root node of a binary tree and infer that the tree is not a balanced binary tree.
Binary balance tree: The depth of the left and right sub-tree of random nodes is not more than 1.
The method of sequential traversal is used, and the depth of the left and right subtree is preserved and compared.
Code:
/* * main.cpp * * Created on:2014.6.12 * author:spike *//*eclipse CDT, gcc 4.8.1*/#include <stdio.h> #include <stdlib.h> #include <string.h>struct binarytreenode {int m_nvalue; binarytreenode* M_pleft; Binarytreenode* m_pright;}; BOOL Isbalanced (binarytreenode* proot, int* pdepth) {if (Proot = = NULL) {*pdepth = 0;return true;} int left, right;if (isbalanced (Proot->m_pleft, &left) && isbalanced (Proot->m_pright, &right)) { int diff = left-right;if (diff>=-1 && diff<=1) {*pdepth = 1 + (left>right?left:right); return true;}} return false;} BOOL Isbalanced (binarytreenode* proot) {int depth = 0;return isbalanced (proot, &depth);} binarytreenode* init (void) {binarytreenode* proot = new Binarytreenode (); proot->m_nvalue = 1; binarytreenode* pNode2 = new Binarytreenode (); Pnode2->m_nvalue = 2; binarytreenode* pNode3 = new Binarytreenode (); Pnode3->m_nvalue = 3; binarytreenode* pNode4 = new Binarytreenode (); Pnode4->m_nvalue = 4; binarytreenode* PNODE5 = new Binarytreenode (); Pnode5->m_nvalue = 5; binarytreenode* pNode6 = new Binarytreenode (); Pnode6->m_nvalue = 6; binarytreenode* PNode7 = new Binarytreenode (); Pnode7->m_nvalue = 7;proot->m_pleft = PNode2; Proot->m_pright = Pnode3;pnode2->m_pleft = PNode4; Pnode2->m_pright = Pnode5;pnode4->m_pleft = NULL; Pnode4->m_pright = Null;pnode5->m_pleft = PNode7; Pnode5->m_pright = Null;pnode7->m_pleft = NULL; Pnode7->m_pright = Null;pnode3->m_pleft = NULL; Pnode3->m_pright = Pnode6;pnode6->m_pleft = NULL; Pnode6->m_pright = Null;return proot;} int main (void) {binarytreenode* proot = init (); bool result = isbalanced (proot);p rintf ("result =%s\n", Result==false? " False ":" true "); return 0;}
Output:
result = True
Programming algorithms-Infer that a binary tree is not a balance tree code (C)