Leetcode 110.Balanced binary tree (balanced binary trees) thinking and method of solving problems

Source: Internet
Author: User

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree was defined as a binary tree in which the depth of the Every node never differ by more than 1.

Idea: Judging whether it is a balanced binary tree, DFS can, recursively determine whether each sub-tree is balanced binary tree, if there are sub-tree is not satisfied, the whole is not satisfied.

The specific code is as follows:

/** * Definition for a binary tree node.  * public class TreeNode {*     int val, *     TreeNode left, *     TreeNode right; *     TreeNode (int x) {val = x;} *} */public class Solution {    /**     * Determine if the binary tree is balanced     * see if the height difference between the left and right subtree is more than 1     * not more than 1 respectively determine whether the left and right sub-tree balance binary tree     */Public Boolean isbalanced (TreeNode root) {        if (root = null)            return true;        if (DEP (0,root) >-Ten)        return true;        return false;    }    Height of the calculation tree    private int dep (int dep,treenode root) {        if (root = null) {            return dep-1;        }        int dep1 = DEP (dep+1,root.left);        int DEP2 = DEP (dep+1,root.right);        If the height difference exceeds 1, return -10        //The subsequent DEP return value will be -10        if (Math.Abs (DEP1-DEP2) > 1) {        return-10;        }        Return dep1 > Dep2? DEP1:DEP2;}    }



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode 110.Balanced binary tree (balanced binary trees) ideas and methods of solving problems

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.