二叉树的层序非递归遍历、判断是否二叉搜索树的非递归算法

层序遍历的非递归算法:

/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector > levelOrder(TreeNode *root) {
vector>result;
vectorlevel;
queuecurrent,next;
TreeNode * t;
if(root==NULL)return result;
current.push(root);
while(!current.empty()){
while(!current.empty()){
t=current.front();
current.pop();
level.push_back(t->val);
if(t->left!=NULL)next.push(t->left);
if(t->right!=NULL)next.push(t->right);
}
result.push_back(level);
level.clear();
swap(current,next);
}
return result;
}
};


判断是否是二叉搜索树的非递归算法:


/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode *root) {
if(root==NULL)return true;
stacks;
TreeNode *p=root;
TreeNode *pre=NULL;
while(!s.empty()||p!=NULL){
while(p!=NULL){
s.push(p);
p=p->left;
}
if(!s.empty()){
p=s.top();
s.pop();
if(pre!=NULL&&p->val<=pre->val)return false;
pre=p;
p=p->right;
}
}
return true;
}
};

相关文档
最新文档