Binary Tree balance check and programmer interview golden collection
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/b6bbed48cd864cf09a34a6ca14a3976f? Rp = 1 & ru =/ta/cracking-the-coding-interview & qru =/ta/cracking-the-coding-interview/question-ranking
Description
Implement a function to check whether the binary tree is balanced. The concept of balance is as follows. For any node in the tree, the height difference between the two Subtrees cannot exceed 1.
Given the pointer TreeNode * root pointing to the root node, return a bool, indicating whether the tree is balanced.
Ideas
The simplest method is that each node uses recursion to solve its depth, and then compares it. However, this will undoubtedly lead to a lot of unnecessary operations, with low efficiency.
We can search for the leaf node from the root node and return its depth in the Backtracking process. In comparison with the layer, once there is any dissatisfaction, it will end directly.
/*struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { }};*/class Balance{public:bool isBalance(TreeNode *root){// write code hereif(root==nullptr)return true;return checkHeight(root)>=0;}int checkHeight(TreeNode *root){if(root==nullptr)return 0;int leftHeight = checkHeight(root->left);if(leftHeight==-1)return -1;int rightHeight = checkHeight(root->right);if(rightHeight==-1)return -1;if(abs(leftHeight-rightHeight)>1)return -1;return max(leftHeight,rightHeight)+1;}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source