1.leetcode种对于树的定义如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
1. 110-balanced binary tree
传送门:https://leetcode.com/problems/balanced-binary-tree/
用的是分治的思想,自己之前一直在纠结的问题是对judge函数的返回值,如果abs已经不满足返回-1的话,那么如何能跳出整个递归出来。
最后解决办法是在判断条件中加入hl==-1 || hr==-1,这样只要有一个-1产生,那么所有的返回值都会变成-1。
int类型函数如果是空的话,返回的还是0.但尽量不依赖编译器的定义。
AC代码:
class Solution {
public:
int judge(TreeNode* root)
{
if(root)
{
int hl=judge(root->left);
int hr=judge(root->right);
if(abs(hl-hr)>1 || hl==-1 || hr==-1) return -1;
int height=hl>hr?hl:hr;
return height+1;
}
return 0;
}
bool isBalanced(TreeNode *root) {
if(judge(root)==-1) return false;
return true;
}
};
传送门:
思路:
自己一开始也想到了用堆栈,但是想到的是用中序遍历,找出所有的值之后再排序查找。
所以先附自己TLE的代码:
class BSTIterator {
public:
stack<int> s;
int a[100]={0};int i=0,j;
int target;
BSTIterator(TreeNode *root) {
if(root==NULL)
target=-1;
else
target=root->val;
test(root);
while(!s.empty())
{
a[i++]=s.top();
s.pop();
}
}
void test(TreeNode* root)
{
while(root)
{
test(root->left);
s.push(root->val);
test(root->right);
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
sort(a,a+i);
for(j=0;j<i;j++)
{
if(a[j]==target && j>0)
return true;
}
return false;
}
/** @return the next smallest number */
int next() {
return a[j-1];
}
};
如果再注意条件的话,只有堆栈/链表才能满足对空间的要求。数组是不能考虑的。