- 找树左下角的值
BFS.
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> q;
int curLevel = 0;
int nextLevel = 0;
q.push(root);
TreeNode* tempNode;
while(q.size())
{
tempNode = q.front();
q.pop();
curLevel--;//事实上,这道题中并不需要维护这个东西...
if(tempNode->right)
{
q.push(tempNode->right);
nextLevel++;
}
if(tempNode->left)
{
q.push(tempNode->left);
nextLevel++;
}
if(!curLevel)
curLevel = nextLevel;
}
return tempNode->val;
}
};
DFS.
为啥DFS比bfs快很多?
class Solution {
public:
int maxLevel = 0;
int res;
int findBottomLeftValue(TreeNode* root) {
res = root->val;
dfs(root, 0);
return res;
}
void dfs(TreeNode* root, int level)
{
if(level > maxLevel)
{
res = root->val;
maxLevel = level;
}
if(root->left)
dfs(root->left, level+1);
if(root->right)
dfs(root->right, level+1);
}
};
- 非递归实现二叉树的前序遍历
by stack. 递归是一个由操作系统完成的一个隐式栈,迭代就是把它显式化。所以,如果是把一个通常递归的方法也是可以借助栈通过迭代来完成的。
class Solution {
public:
vector<int> ans;
vector<int> preorderTraversal(TreeNode* root) {
if(!root)
return ans;
stack<TreeNode*> s;
s.push(root);
while(s.size())
{
TreeNode* tempNode = s.top();
ans.push_back(tempNode->val);
s.pop();
if(tempNode->right)
s.push(tempNode->right);
if(tempNode->left)
s.push(tempNode->left);
}
return ans;
}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> ans;
if(!root)
return ans;
stack<TreeNode*> s;
TreeNode* prev=nullptr;
while(root || s.size())
{
while(root)
{
s.push(root);
root = root->left;
}
root = s.top();
s.pop();
if(!root->right || root->right == prev) //如果右边为空或者已经访问过
{
ans.push_back(root->val);
prev = root;
root = nullptr;
}
else
{
s.push(root);
root = root->right;
}
}
return ans;
}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
if(!root)
return ans;
stack<TreeNode*> s;
while(root || s.size())
{
while(root)
{
s.push(root);
root = root->left;
}
root = s.top();
s.pop();
ans.push_back(root->val);
if(root->right)
root = root->right;
else
root = nullptr;
}
return ans;
}
};
- 修剪二叉搜索树
二叉搜索树的每一个根节点都大于等于左子树的节点,小于等于右子树的每一个节点。
递归。
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(!root)
return nullptr;
if(root->val >= low && root->val<=high)
{
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
if(root->val<low)
return trimBST(root->right, low, high);
else
return trimBST(root->left, low, high);
}
};