Binary Tree balance check and programmer interview golden collection

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.