39.题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路:平衡二叉树定义(AVL):它或者是一颗空树,或者具有以下性质的二叉树:它的左子树和右子树的深度之差(平衡因子)的绝对值不超过1,且它的左子树和右子树都是一颗平衡二叉树。平衡因子(bf):结点的左子树的深度减去右子树的深度,那么显然-1<=bf<=1
1.从下往上计算每个节点的深度,存在问题:即使子树不符合,也要遍历整棵树才能终止。
2.从下往上计算每个节点的深度,每次进行判断,子树不符合就退出不进行遍历
1.
class Solution {
public:
bool flag=true;
int getDepth(TreeNode* pRoot)
{
if(pRoot==NULL)
return 0;
int left=getDepth(pRoot->left);
int right=getDepth(pRoot->right);
if(abs(left-right)>1)
flag=false;
return 1+max(left,right);
}
bool IsBalanced_Solution(TreeNode* pRoot) {
getDepth(pRoot);
return flag;
}
};
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.flag=True
def process(self,pRoot):
if pRoot==None:
return 0
left=self.process(pRoot.left)
right=self.process(pRoot.right)
if abs(left-right)>1:
self.flag=False
return max(left,right)+1
def IsBalanced_Solution(self, pRoot):
self.process(pRoot)
return self.flag
# write code here
2.
class Solution {
public:
bool getDepth(TreeNode* pRoot,int &dp)
{
if(pRoot==NULL)
return true;
int left=0,right=0;
if(getDepth(pRoot->left,left) && getDepth(pRoot->right,right))
{
if(abs(left-right)>1)
return false;
dp=max(left+1,right+1);
return true;
}
return false;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
int dp=0;
return getDepth(pRoot,dp);
}
};
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def process(self,pRoot,deep):
if pRoot==None:
return True
left=[0]
right=[0]
if self.process(pRoot.left,left) and self.process(pRoot.right,right):
if abs(left[0]-right[0])>1:
return False
deep[0]=max(left[0],right[0])+1
return True
return False
def IsBalanced_Solution(self, pRoot):
deep=[0]//固定存储位置,为下文的引用准备。
return self.process(pRoot,deep)
# write code here
40.题目描述
一个整型数组里除了两个数字之外,其他的数字都出现了偶数次。请写程序找出这两个只出现一次的数字。
思路:首先:位运算中异或的性质:两个相同数字异或=0,一个数和0异或还是它本身。
当只有一个数出现一次时,我们把数组中所有的数,依次异或运算,最后剩下的就是落单的数,因为成对儿出现的都抵消了。
依照这个思路,我们来看两个数(我们假设是AB)出现一次的数组。我们首先还是先异或,剩下的数字肯定是A、B异或的结果,这个结果的二进制中的1,表现的是A和B的不同的位。我们就取第一个1所在的位数,假设是第3位,接着把原数组分成两组,分组标准是第3位是否为1。如此,相同的数肯定在一个组,因为相同数字所有位都相同,而不同的数,肯定不在一组。然后把这两个组按照最开始的思路,依次异或,剩余的两个结果就是这两个只出现一次的数字。
空间复杂度O(1)
class Solution {
public:
int getindex(int bitxor)
{
int index=0;
while((bitxor & 1 )==0 && index<32)
{
bitxor=bitxor>>1;
++index;
}
return index;
}
bool isbit1(int data,int index)
{
return ((data>>index) & 1) ;
}
void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {
if(data.size()<2)
return;
int bitxor=0;
for(auto i:data)
bitxor^=i;
int indexof1=getindex(bitxor);
for(int i=0;i<data.size();++i)
{
if(isbit1(data[i],indexof1))
*num1^=data[i];
else
*num2^=data[i];
}
}
};
# -*- coding:utf-8 -*-
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
a=[]
for i in array:
if array.count(i)==1:
a.append(i)
return a
# write code here