LeetCode110 Blanced Binary Tree Java 題解

來源:互聯網
上載者:User

標籤:balancedbinarytree   java   leetcode   

題目:

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

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


題解:

判斷一顆二叉樹是不是平衡二叉樹  ,平衡二叉樹是每個節點都滿足指左右子樹的高度差小於1

我們通過計算每一個節點的左右高度差  一旦發現有不滿足的節點就將返回值置為-1   這兩句代碼if(left==-1) return -1;
if(right==-1) return -1保證只要出現一個高度差為-1的最終返回結果必然為-1,也就是說最終可以根據返回值是不是-1判斷是不是平衡二叉樹


代碼:

public static boolean isBalanced(TreeNode root) {if(treeHight(root)==-1)return false;else return true;            }public static int treeHight(TreeNode root){if(root==null)return 0;else {int left=treeHight(root.left);int right=treeHight(root.right);if(left==-1) return -1;if(right==-1) return -1;if(Math.abs(left-right)>1)return -1;else {return 1+Math.max(treeHight(root.left), treeHight(root.right));}}}


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

LeetCode110 Blanced Binary Tree Java 題解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.