[容易]平衡二叉树

题目来源:http://www.lintcode.com/zh-cn/problem/balanced-binary-tree/

C++版 VS2012测试通过:

 1 #include <iostream>
 2 #include <vector>
 3 #include <queue>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 class TreeNode {
 8 public:
 9     int val;
10     TreeNode *left, *right;
11     TreeNode(int val=-1) {
12         this->val = val;
13         this->left = this->right = NULL;
14     }
15 };
16 
17 //以前序遍历创建二叉树
18 //输入12##34##5##,测试结果是3,true
19 //输入1#34##5##,测试结果是-1,false
20 void CreateBiTree(TreeNode **T)//*T是指向BiTNode的指针
21 {
22     *T=new TreeNode;
23     if(*T==NULL)//如果*T还是指向NULL,表示内存分配失败,退出程序
24         exit(OVERFLOW);
25     char ch;
26     cin>>ch;
27       if(ch=='#')
28         *T=NULL;
29     else
30     {
31         (*T)->val=ch-'0';//*T指向的节点的data分配内容,即生成根节点
32         CreateBiTree(&((*T)->left));//创建&(*T)->lchild临时变量,传入CreateBiTree,构造左子树
33         CreateBiTree(&((*T)->right));//创建&(*T)->rchild临时变量,传入CreateBiTree,构造右子树
34     }
35 }
36 
37 class Solution {
38 public:
39      /**
40      * @param root: The root of binary tree.
41      * @return: True if this Binary tree is Balanced, or false.
42      */
43     int depth(TreeNode *root) {
44         if (root == NULL) {
45             return 0;
46         }
47         int left = depth(root->left);
48         int right = depth(root->right);
49         if (left == -1 || right == -1 || abs(left - right) > 1) {
50             return -1;
51         }
52         return max(left, right) + 1;
53     }
54     bool isBalanced(TreeNode *root) {
55         return depth(root) != -1;
56     }
57 };
58 
59 //测试
60 int main()
61 {
62     Solution s;
63     TreeNode **pp;//定义指向BiTNode的二级指针pp
64     TreeNode *p;//定义指向BiTNode的指针p
65     pp=&p;//pp指向p
66     p=NULL;//初始化p指向NULL
67     CreateBiTree(pp);//传入指向p的地址,创建二叉树
68     cout<<s.depth(p);
69     cout<<endl;
70     cout<<s.isBalanced(p);
71 }

Python2.7版 spider测试通过:

 1 # -*- coding: utf-8 -*-
 2 
 3 class TreeNode:
 4    def __init__(self,val,left,right):
 5        self.val=val
 6        self.left=left
 7        self.right=right
 8 
 9 class Solution:
10     """
11     @param root: The root of binary tree.
12     @return: True if this Binary tree is Balanced, or false.
13     """
14     def isBalanced(self, root):
15         balanced, _ = self.validate(root)
16         return balanced
17         
18     def validate(self, root):
19         if root is None:
20             return True, 0
21             
22         balanced, leftHeight = self.validate(root.left)
23         if not balanced:
24             return False, 0
25         balanced, rightHeight = self.validate(root.right)
26         if not balanced:
27             return False, 0
28             
29         return abs(leftHeight - rightHeight) <= 1, max(leftHeight, rightHeight) + 1
30 
31 #测试
32 if __name__=='__main__':
33    s=Solution()
34    node2=TreeNode(2,None,None)
35    node4=TreeNode(4,None,None)
36    node5=TreeNode(5,None,None)
37    node3=TreeNode(3,node4,node5)
38    root=TreeNode(1,node2,node3)
39    print s.validate(root)
40    print s.isBalanced(root)
posted @ 2016-07-02 23:15  Pearl_zju  阅读(168)  评论(0编辑  收藏  举报