Leetcode: balanced_binary_tree

Source: Internet
Author: User

I. Question

Determine whether the given binary tree is a balanced binary tree, that is, the depth difference of each node is not greater than 1

Ii. Analysis

We generally think of recursion for tree problems, and the same is true for this question. We only need to determine whether the left and right subtree of each node are balanced.

Recursion, recursion, recursion ......

 


/*** Definition for binary tree * struct treenode {* int val; * treenode * left; * treenode * right; * treenode (int x): Val (x ), left (null), right (null) {}*}; */class solution {public: bool isbalanced (treenode * root) {If (depthcheck (Root) = 0) return true; If (ABS (depthcheck (root-> left)-depthcheck (root-> right)> 1) return false; elsereturn isbalanced (root-> left) & isbalanced (root-> right);} int depthchec K (treenode * root) {If (! Root) return 0; int depthl = depthcheck (root-> left) + 1; int depthr = depthcheck (root-> right) + 1; return depthl> depthr? Depthl: depthr ;}};


Leetcode: balanced_binary_tree

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.