Balanced Binary Tree (Binary Tree DFS)

Source: Internet
Author: User

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 subtreesEveryNode never differ by more than 1.

Determine whether a tree is a balanced binary tree.

Idea: typical recursion: Check whether the depth difference between the left and right subtree is less than or equal to 1 from the first root node, then, let's see if both the left and right course trees of the root node meet the requirements.

Code:

/*** Definition for binary tree * struct TreeNode {* int val; * TreeNode * left; * TreeNode * right; * TreeNode (int x): val (x ), left (NULL), right (NULL) {}*}; */class Solution {private: int maxdepth; public: void solve (TreeNode * root, int depth) {if (root = NULL) return; if (depth> maxdepth) maxdepth = depth; solve (root-> left, depth + 1); solve (root-> right, depth + 1);} int getDepth (TreeNode * root) {maxdepth = 0; solve (root, 1); return maxdepth;} bool isBalanced (TreeNode * root) {if (root = NULL) return true; int l, r; if (root-> left! = NULL) {l = getDepth (root-> left);} else {l = 0;} if (root-> right! = NULL) {r = getDepth (root-> right);} else {r = 0;} return abs (l-r) <= 1 & isBalanced (root-> left) & isBalanced (root-> right );}};

 

Balanced Binary Tree (Binary Tree DFS)

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.