Balanced Binary Tree [LeetCode]

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Solution: 

 1     bool helperBalanced(int *depth, TreeNode * root){

 2         if(root->left == NULL && root->right == NULL){

 3             (*depth) = 1;

 4             return true;

 5         }

 6         

 7         int left_depth = 0;

 8         int right_depth = 0;

 9         if(root->left != NULL){

10             if(helperBalanced(&left_depth, root->left) == false)

11                 return false;

12         }

13         

14         if(root->right != NULL){

15             if(helperBalanced(&right_depth, root->right) == false)

16                 return false;

17         }

18         

19         if(abs(right_depth - left_depth) > 1)

20             return false;

21         

22         (*depth) = max(left_depth, right_depth) + 1;

23             

24         return true;

25     }

26     

27     bool isBalanced(TreeNode *root) {

28         if(root == NULL)

29             return true;

30         int depth= 0;

31         return helperBalanced(&depth, root);

32     }

 

你可能感兴趣的:(LeetCode)