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.