Question: Enter the root node of a binary tree to determine whether the tree is balanced. If the depth difference between left and right Subtrees of any node in a binary tree does not exceed 1, it is a balanced binary tree.
Note: whether the binary tree is a binary sorting tree is not considered here.
Solution: 1. Traverse Binary Trees in descending order; 2. recursion.
Core algorithms:
Bool isbalanced (ptree PT, int * depth) {If (! Pt) // parameter judgment {* depth = 0; return true;} // returns int left, right; if (isbalanced (Pt-> lchild, & left) & isbalanced (Pt-> rchild, & right) {int differ = left-right; if (differ> =-1 & differ <= 1) {// record depth * depth = (left> right )? Left + 1: Right + 1; return true;} return false;} bool isbalanced (ptree root) // input the root node of the Binary Tree {int depth = 0; return isbalanced (root, & depth );}
Complete program:
/********************************* Determine whether a binary tree is a balanced binary tree rowandjj2014/7/13 ********************************/# include <iostream> using namespace STD; typedef struct _ node _ {int data; struct _ node _ * lchild; struct _ node _ * rchild;} treenode, * ptree; void create (ptree * PT) {int e; cin> E; If (E! =-1) {* PT = (treenode *) malloc (sizeof (treenode); If (! Pt) {exit (-1) ;}( * PT)-> DATA = E; (* PT)-> lchild = NULL; (* PT)-> rchild = NULL; create (& (* PT)-> lchild); Create (& (* PT)-> rchild) ;}} bool isbalanced (ptree PT, int * depth) {If (! Pt) {* depth = 0; return true;} int left, right; if (isbalanced (Pt-> lchild, & left) & isbalanced (Pt-> rchild, & right) {int differ = left-right; if (differ >=- 1 & differ <= 1) {* depth = (left> right )? Left + 1: Right + 1; return true;} return false;} bool isbalanced (ptree root) // input the root node of the Binary Tree {int depth = 0; return isbalanced (root, & depth);} void travel (ptree pt) {If (PT! = NULL) {travel (Pt-> lchild); travel (Pt-> rchild); cout <Pt-> data <";}} int main () {ptree pt; Create (& pt); travel (PT); cout <Endl; cout <isbalanced (PT); Return 0 ;}