12. Two Fork tree balance check

Source: Internet
Author: User

Title Description

Implement a function to check whether the two fork tree is balanced, the balance is defined as follows, for any node in the tree, its two sub-tree height difference of not more than 1.

Given a pointer to the root node treenode* root, return a bool, representing whether the tree is balanced.

Thought: Divide and conquer (means) recursion (processing method)

The code is as follows:

Import Java.util.*;/*public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    Public TreeNode (int val) {        this.val = val;    }} */public class Balance {public    Boolean isbalance (TreeNode root) {        if (root==null) return true;        Boolean lef= isbalance (root.left);        Boolean rig=isbalance (root.right);        int leflength=deepth (root.left);        int riglength=deepth (root.right);        if (lef && rig && math.abs (leflength-riglength) <=1)            return true;        else            return false;            }    int deepth (TreeNode root) {        if (root==null) return 0;        int leftdeepth=deepth (root.left);        int rightdeepth=deepth (root.right);        Return Math.max (leftdeepth,rightdeepth) +1;}    }

  

12. Two Fork tree balance check

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.