# Leetcode: balanced_binary_tree, leetcode

Source: Internet
Author: User

Leetcode: balanced_binary_tree, leetcode

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 depthcheck(TreeNode *root){if(!root)return 0;int depthL=depthcheck(root->left)+1;int depthR=depthcheck(root->right)+1;return depthL > depthR ? depthL : depthR;}};`

How to program leetcode

Step 1: Enter www.leetcode.com in the browser
Step 2: click Register in the upper right corner.
Step 3: Register and log on, and click Online judge in the upper right corner.
Step 4: You may be logged on again. Click sing in instead of sign up and enter the user name and password to log on:
Step 5: select a question, select a language, enter the code in the code editor, and submit solution. The system will judge whether the result is correct or not. All submitted code systems will be saved for you, which can be viewed in my submission.

What is leetcode?

There are many programming and interview questions, which can be compiled and run online. It is difficult. If you can do it all by yourself, it is very helpful for large companies. I just did the questions there.

Related Keywords:

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.