文章目录
求二叉树的层序遍历
给定一个二叉树,返回该二叉树层序遍历的结果
实现思路:BFS, 用队列保存每一层节点
1️⃣先将根节点入队
2️⃣当队列不为空
①求出当前队列len(即当前层)
②取出前len个节点,值存起来
③如果有孩子节点,压入队列
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > levelOrder(TreeNode* root) {
// write code here
//实现思路,用队列保存节点,vector保存每一层遍历结果
vector<vector<int>> res;
if(root==nullptr)
return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
vector<int> tmp;
int n=q.size();
for(int i=0;i<n;i++){
TreeNode* t=q.front();
q.pop();
tmp.push_back(t->val);
if(t->left)
q.push(t->left);
if(t->right)
q.push(t->right);
}
res.push_back(tmp);
}
return res;
}
};
本题还有一个变式:之字形遍历,思路一致,只需要用一个bool标识奇数层还是偶数层,偶数层reverse一下即可
在二叉树中寻找最近的公共祖先
最近公共祖先和o1,o2有三种关系:
- o1,o2分别在祖先左右两侧
- 祖先是o1,o2在祖先左/右侧
- 祖先是o2,o1在祖先左/右侧
使用dfs深度遍历,如果节点为o1,o2中其中一个直接返回,如果节点超过叶子节点也返回
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
// write code here
return CommonAncestor(root,o1,o2)->val;
}
TreeNode* CommonAncestor(TreeNode* root,int o1,int o2){
if(root==nullptr||root->val==o1||root->val==o2)
return root;
TreeNode* left=CommonAncestor(root->left, o1, o2);
TreeNode* right=CommonAncestor(root->right, o1, o2);
if (left == nullptr) {
// 都在右侧
return right;
}
if (right == nullptr) {
// 都在左侧
return left;
}
return root; // 在左右两侧
}
};
二叉树的先序、中序、后序遍历
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
vector<int> pre;
vector<int> in;
vector<int> post;
class Solution {
public:
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型vector<vector<>>
*/
void preorder(TreeNode* root){
if(root