Tree_Graph 判斷是否平衡二叉樹 @CareerCup_PHP教程

來源:互聯網
上載者:User
Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.


平衡二叉樹的定義為:它是一棵空樹或它的左右兩個子樹的高度差的絕對值不超過1, 並且左右兩個子樹都是一棵平衡二叉樹。


思路:

1)先寫一個遞迴的樹的高度函數,然後檢查子樹的高度差是否大於1

2)最佳化:把檢查子樹高度差是否大於1的邏輯放在求樹的高度的遞迴函式中,並且遇到非平衡就及時返回。


註:

這道題不同於問一棵樹是否平衡(這棵樹任意兩個葉子結點到根結點的距離之差不大於1):


<喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+PGJyPgo8L3A+CjxwPsjnyc/NvKOszqrGvbritv6y5sr3o6y1q7K7xr264qGjPC9wPgo8cD7F0LbP0ru/w8r3yse38ca9uuK/ydLUx/PK97XE1+6087jftsi6zdfu0KG437bI1q6y7srHt/G089PaMaGjPC9wPgo8cD7H88r3tcTX7tChuN+2yL/Jss6/vKO6aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZmlnaHRmb3J5b3VyZHJlYW0vYXJ0aWNsZS9kZXRhaWxzLzEyODUxMjMxPC9wPgo8cD48YnI+CjwvcD4KPHA+we3Su9bWveK3qMrHv8nS1NPD1tDQ8rHpwPrH87XDyvfA77XEw7/Su7j20rbX07XEuN+2yKOsyLu687/JtcOhozwvcD4KPHA+ss6/vKO6aHR0cDovL2hhd3N0ZWluLmNvbS9wb3N0cy80LjEuaHRtbDwvcD4KPHA+PGJyPgo8L3A+CjxwPs/Cw+bKx8XQts/Kx7fxxr264rb+subK97XEtPrC66O6PC9wPgo8cD48cHJlIGNsYXNzPQ=="brush:java;">package Tree_Graph;import CtCILibrary.AssortedMethods;import CtCILibrary.TreeNode;public class S4_1 {// 遞迴判斷樹是否平衡二叉樹// Time: O(N^2)public static boolean isBalanced(TreeNode root) {if (root == null) {return true;}int heightDiff = getHeight(root.left) - getHeight(root.right);if(Math.abs(heightDiff) > 1) {// 非平衡return false;} else {return isBalanced(root.left) && isBalanced(root.right);}}// 遞迴獲得樹的高度public static int getHeight(TreeNode root) {if (root == null) {return 0;}return Math.max(getHeight(root.left), getHeight(root.right)) + 1;}// ========================== Improved version 最佳化版// 把判斷是否平衡的邏輯放在checkHeight函數裡,邊計算高度,// 邊判斷是否平衡,如果不平衡,直接返回-1// Time: O(N), Space: O(H), H: height of treepublic static boolean isBalanced2 (TreeNode root) {if (checkHeight(root) == -1) {return false;} else{return true;}}// 邊計算高度邊判斷是否平衡public static int checkHeight (TreeNode root) {if (root == null) {return 0;}int leftHeight = checkHeight(root.left);if (leftHeight == -1) {return -1;}int rightHeight = checkHeight(root.right);if (rightHeight == -1) {return -1;}int heightDiff = leftHeight - rightHeight;if (Math.abs(heightDiff) > 1) {return -1;}return Math.max(leftHeight, rightHeight) + 1;}public static void main(String[] args) {// Create balanced treeint[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};TreeNode root = TreeNode.createMinimalBST(array);System.out.println("Root? " + root.data);System.out.println("Is balanced? " + isBalanced(root));// Could be balanced, actually, but it's very unlikely...TreeNode unbalanced = new TreeNode(10);for (int i = 0; i < 10; i++) {unbalanced.insertInOrder(AssortedMethods.randomIntInRange(0, 100));}System.out.println("Root? " + unbalanced.data);System.out.println("Is balanced? " + isBalanced(unbalanced));}}



http://www.bkjia.com/PHPjc/735868.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/735868.htmlTechArticleImplement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.