Balanced Binary Tree

來源:互聯網
上載者:User

標籤:style   blog   color   使用   io   for   ar   div   代碼   

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. 空樹是一顆平衡二叉樹

2. 它的左子樹和右子樹的高度差不超過1

3. 它的左子樹和右子樹也是平衡二叉樹

故判斷這棵樹是否是平衡二叉樹,不僅要求樹的高度,也要判斷左右子樹是否均為平衡二叉樹,使用樹的後序遍曆,求樹高度的時候同時判斷這棵樹是否是平衡二叉書,代碼如下:

 1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     bool isBalanced(TreeNode *root) {13         return getdepth(root) > -1;14     }15     16     int getdepth(TreeNode* root) {  //返回正常高度,說明是平衡二叉樹,否則返回-117         if( !root ) return 0;   //空樹是平衡二叉樹,返回018         int leftdepth = getdepth(root->left);   //左子樹高度19         int rightdepth = getdepth(root->right); //右子樹高度20         //左子樹不是  或  右子樹不是   或   左右子樹高度差超過121         if( leftdepth == -1 || rightdepth == -1 || abs(leftdepth-rightdepth) > 1 ) return -1;22         return max(leftdepth, rightdepth)+1;23     }24 };

 

Balanced Binary Tree

聯繫我們

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