算法日志7:欢乐树朋友
前言
Happy Tree Friends!
《欢乐树的朋友们》是一部画风可爱的合家欢动漫,强烈推荐
树的前中后序遍历,其实指的就是中间节点的遍历顺序,只要大家记住 前中后序指的就是中间节点的位置就可以了。
看如下中间节点的顺序,就可以发现,中间节点的顺序就是所谓的遍历方式
前序遍历:中左右
中序遍历:左中右
后序遍历:左右中
树的前中后序遍历,都是深度优先搜索,树的层序遍历,是广度优先搜索,也是限制高度的深度优先搜索(限制层数的中序遍历)
二叉树的前序递归遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> res;
void f_travel(TreeNode* cur){
if(cur == nullptr){
return;
}
if(cur->left == nullptr && cur->right == nullptr) {
res.push_back(cur->val);
return;
}
res.push_back(cur->val);
if(cur->left!=nullptr){
f_travel(cur->left);
}
if(cur->right!= nullptr){
f_travel(cur->right);
}
return;
}
vector<int> preorderTraversal(TreeNode* root) {
f_travel(root);
return res;
}
};
后序
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void b_travel(TreeNode * cur, vector<int> &arr){
if(cur == nullptr) return;
b_travel(cur->left,arr);
b_travel(cur->right,arr);
arr.push_back(cur->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> arr;
b_travel(root,arr);
return arr;
}
};
中序
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void m_travel(TreeNode * cur, vector<int> &arr){
if(cur == nullptr) return;
m_travel(cur->left,arr);
arr.push_back(cur->val);
m_travel(cur->right,arr);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> arr;
m_travel(root,arr);
return arr;
}
};
二叉树的前序迭代遍历
(注意代码中空节点不入栈)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode *> st;
vector<int> res;
if(root ==NULL) return res;
st.push(root);
while(!st.empty()){
TreeNode* tmp = st.top();
res.push_back(tmp->val);
st.pop();
if(tmp -> right) st.push(tmp->right);
if(tmp -> left) st.push(tmp->left);
}
return res;
}
};
后序,思路是 中右左, 在reverse数组
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> res;
if(root==nullptr) return res;
st.push(root);
while(!st.empty()){
TreeNode* tmp = st.top();
res.push_back(tmp->val);
st.pop();
if(tmp->left) st.push(tmp->left);
if(tmp->right) st.push(tmp->right);
}
reverse(res.begin(), res.end());
return res;
}
};
中序
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<int> st;
if(root == nullptr) return res;
TreeNode* cur = root;
while(!cur && !st.emptu()){
if(!cur){
st.push(cur)
cur= cur->left;
}
else{
cur = st.top(); // 从栈里弹出的数据,就是要处理的数据(放进result数组里的数据)
st.pop();
result.push_back(cur->val); // 中
cur = cur->right;
}
}
}
};
层序遍历1,2
递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void travel(TreeNode* cur, vector<vector<int>> &res, int level){
if(cur == nullptr) return;
if(level >= res.size()) res.push_back(vector<int>());
res[level].push_back(cur->val);
travel(cur->left,res,level+1);
travel(cur->right,res,level+1);
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
int level = 0;
travel(root, res, level);
reverse(res.begin(), res.end());
return res;
}
};
迭代
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> q;
if(root == nullptr) return res;
q.push(root);
while(!q.empty()){
int len = q.size();
vector<int> subres;
for(int i =0 ;i< len;i++){
TreeNode* tmp = q.front();
q.pop();
subres.push_back(tmp->val);
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
res.push_back(subres);
}
reverse(res.begin(), res.end());
return res;
}
};
二叉树的右视图
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
if(root == nullptr) return res;
queue<TreeNode *> q;
q.push(root);
while(!q.empty()){
int len = q.size();
for(int i =0; i<len;i++){
TreeNode* tmp = q.front();
if(i == len-1){
res.push_back(tmp->val);
}
q.pop();
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
}
return res;
}
};
二叉树的层平均值
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> res;
while(root == nullptr) return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
double sum = 0;
int len = q.size();
for(int i =0 ;i<len;i++){
TreeNode* tmp = q.front();
q.pop();
sum+=tmp->val;
if(tmp ->left) q.push(tmp->left);
if(tmp -> right) q.push(tmp->right);
}
res.push_back(sum/len);
}
return res;
}
};
N叉树层序遍历
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
vector<vector<int>> res;
if(root == nullptr) return res;
queue<Node*> q;
q.push(root);
while(!q.empty()){
int len = q.size();
vector<int> sub_res;
for(int i =0 ;i <len;i++){
Node* tmp = q.front();
q.pop();
sub_res.push_back(tmp->val);
for(auto i: tmp->children){
if(i) q.push(i);
}
}
res.push_back(sub_res);
}
return res;
}
};
在每个树行中找最大值
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> res;
if(root == nullptr) return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int max = INT32_MIN;
int len = q.size();
for(int i =0; i<len;i++){
TreeNode* tmp = q.front();
q.pop();
max = max>tmp->val?max:tmp->val;
tmp->left?q.push(tmp->left):void(0);
tmp->right?q.push(tmp->right):void(0);
}
res.push_back(max);
}
return res;
}
};
填充每个节点的下一个右侧节点指针
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node* _left, Node* _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}
};
*/
class Solution {
public:
Node* connect(Node* root) {
queue<Node*> q;
if(root == nullptr) return root;
q.push(root);
while(!q.empty()){
int len = q.size();
Node* vhead = new Node();
Node* cur = vhead;
while(len--){
Node* tmp = q.front();
q.pop();
cur->next = tmp;
// cout<<tmp->val;
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
cur = cur->next;
}
}
return root;
}
};
二叉树的最大深度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
int res = 0;
queue<TreeNode*> q;
if(root == nullptr) return res;
q.push(root);
while(!q.empty()){
int len = q.size();
res++;
for(int i =0 ;i < len;i++){
TreeNode* tmp = q.front();
q.pop();
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
}
return res;
}
};
二叉树最小深度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
int res = 0;
queue<TreeNode*> q;
if(root == nullptr) return res;
q.push(root);
while(!q.empty()){
int len = q.size();
res++;
for(int i =0 ;i < len;i++){
TreeNode* tmp = q.front();
q.pop();
if(!tmp->left && !tmp->right) return res;
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
}
return res;
}
};
翻转二叉树
前序迭代
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
stack<TreeNode*> st;
if(root == nullptr) return root;
st.push(root);
while(!st.empty()){
TreeNode*tmp = st.top();
TreeNode* trans = new TreeNode();
trans = tmp->left;
tmp->left = tmp->right;
tmp->right = trans;
st.pop();
if(tmp->right) st.push(tmp->right);
if(tmp->left) st.push(tmp->left);
}
return root;
}
};
层序迭代
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
queue<TreeNode*> q;
if(root == nullptr) return root;
q.push(root);
while(!q.empty()){
int len = q.size();
while(len--){
TreeNode*tmp = q.front();
q.pop();
TreeNode* trans = new TreeNode();
trans = tmp->left;
tmp->left = tmp->right;
tmp->right = trans;
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
}
return root;
}
};
对称二叉树
迭代,超多限制条件
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
stack<TreeNode*> st1;
stack<TreeNode*> st2;
if(root == nullptr) {
cout<< "root is nullptr";
return 1;
}
if(!root->left && !root->right) return true;
if(!root->left || !root->right){
cout<<"root's left or right is null";
return false;
}
st1.push(root->left);
st2.push(root->right);
vector<int>res1;
vector<int>res2;
while(!st1.empty()&& !st2.empty()){
TreeNode*tmp = st1.top();
st1.pop();
TreeNode*tmp2 = st2.top();
st2.pop();
if(tmp->val != tmp2->val) {cout<<0;return false;}
if(tmp->left == nullptr && tmp2->right != nullptr) {cout<<1;return false;}
if(tmp->left != nullptr && tmp2->right == nullptr) {cout<<2;return false;}
if(tmp->right != nullptr && tmp2->left == nullptr) {cout<<3;return false;}
if(tmp->right == nullptr && tmp2->left != nullptr) {cout<<4;return false;}
if(tmp->left) st1.push(tmp->left);
if(tmp->right) st1.push(tmp->right);
if(tmp2->right) st2.push(tmp2->right);
if(tmp2->left) st2.push(tmp2->left);
}
if(st1.size() == st2.size()) {cout<<st1.size()<<" "<<st2.size()<<endl;return 1;}
else {cout<<st1.size()<<" "<<st2.size()<<" "<<6;return 0;}
}
};
相同的树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
queue<TreeNode*> que;
if(p == nullptr && q == nullptr) return true;
if(p == nullptr || q==nullptr) return false;
que.push(p);
que.push(q);
while(!que.empty()){
TreeNode* l = que.front();que.pop();
TreeNode* r = que.front();que.pop();
if(!l && !r) continue;
if(!l||!r||(l->val != r->val)) return false;
que.push(l->left);
que.push(r->left);
que.push(l->right);
que.push(r->right);
}
cout<<"yse";
return true;
}
};
另一棵树的子树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool travel(TreeNode* cur1, TreeNode*cur2){
if(!cur1 && !cur2) return true;
if(!cur1 || !cur2||(cur1->val != cur2->val)) return false;
bool l = travel(cur1->left, cur2->left);
bool r = travel(cur1->right, cur2->right);
return l&r;
}
bool f_travel(TreeNode* cur, TreeNode*subroot){
if(travel(cur, subroot)) return true;
if(cur == nullptr) return false;
return (f_travel(cur->left, subroot) || f_travel(cur->right, subroot));
}
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
return f_travel(root,subRoot);
}
};
n叉树最大深度
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
int maxDepth(Node* root) {
queue<Node*> q;
if(root == nullptr) return 0;
int res = 0;
q.push(root);
while(!q.empty()){
int len = q.size();
res++;
for(int i =0; i<len; i++){
Node* tmp = q.front();
q.pop();
for(auto i:tmp->children){
if(i) q.push(i);
}
}
}
return res;
}
};
完全二叉树的节点个数
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
stack<TreeNode*> st;
int res = 0;
if(root == nullptr) return res;
st.push(root);
while(!st.empty()){
TreeNode* tmp = st.top();
st.pop();
res++;
if(tmp->left) st.push(tmp->left);
if(tmp->right) st.push(tmp->right);
}
return res;
}
};
平衡二叉树
一开始写的代码,
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int get_height(TreeNode * cur){
if(cur == nullptr) return 0;
int l_height = get_height(cur->left);
int r_height = get_height(cur->right);
return l_height>r_height? l_height+1:r_height+1;
}
bool isBalanced(TreeNode* root) {
if(root == nullptr) return 1;
int l = get_height(root->left);
int r = get_height(root->right);
if(r-l > 1 || r-l<-1) {
cout<<"r:"<<r<<" l:"<<l<<endl;
return 0;
}
return 1;
}
};
发现报错,原因是只检查了根节点左右的两个子树的高度,但是还要保证,在遍历过程中,每个子树都要是平衡二叉树,例如下面的例子

虽然左右子树等高,但是左右字数已经本身已经不是平衡二叉树了
改进后代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int get_height(TreeNode * cur){
if(cur == nullptr) return 0;
int l_height = get_height(cur->left);
if(l_height == -1) return -1;
int r_height = get_height(cur->right);
if(r_height == -1) return -1;
if(l_height-r_height>1 || l_height-r_height<-1) return -1;
return l_height>r_height? l_height+1:r_height+1;
}
bool isBalanced(TreeNode* root) {
if(root == nullptr) return 1;
int res = get_height(root);
return res == -1?0:res;
}
};
左叶子之和
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void getsum(TreeNode* cur, int& sum){
if(cur == nullptr) return;
if(cur->left && !cur->left->left &&!cur->left->right){
sum+=cur->left->val;
}
if(cur->left) getsum(cur->left,sum);
if(cur->right) getsum(cur->right,sum);
}
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
getsum(root, sum);
return sum;
}
};
找树左下角的值
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
TreeNode * res = q.front();
while(!q.empty()){
int len = q.size();
res = q.front();
for(int i= 0; i<len;i++){
TreeNode * tmp = q.front();
q.pop();
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
}
return res->val;
}
};
路径总和
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool travel(TreeNode* cur, int targetSum, int& sum){
if(!cur->left && !cur->right){
int res = sum + cur->val;
if(res == targetSum) return true;
else return false;
}
bool l = false, r = false;
if (cur->left){
sum+=cur->val;
l = travel(cur->left, targetSum, sum);
sum-=cur->val;
} // 左子树非空时递归
if (cur->right){
sum+=cur->val;
r = travel(cur->right, targetSum, sum); // 右子树非空时递归
sum-=cur->val;
}
return l||r;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root == nullptr) return false;
int sum = 0;
return travel(root, targetSum, sum);
}
};
路径总和2
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> res_arr;
vector<int> path;
void travel(TreeNode* cur, int targetSum, int& sum){
if(!cur->left && !cur->right){
int res = sum + cur->val;
if(res == targetSum) {
path.push_back(cur->val);
res_arr.push_back(path);
path.pop_back();
return;
}
else return;
}
if (cur->left){
sum+=cur->val;
path.push_back(cur->val);
travel(cur->left, targetSum, sum);
sum-=cur->val;
path.pop_back();
} // 左子树非空时递归
if (cur->right){
sum+=cur->val;
path.push_back(cur->val);
travel(cur->right, targetSum, sum); // 右子树非空时递归
sum-=cur->val;
path.pop_back();
}
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
if(root == nullptr) return res_arr;
int sum =0;
travel(root,targetSum, sum);
return res_arr;
}
};
从中序与后序遍历序列构造二叉树
一定要注意,空指针nullptr,或者空NULL是没有类型的
假设cur == nullptr, 那么cur是没有val,left,right等属性的,访问会出错
一开始构造的root节点,默认左右节点都是nullptr,所以当传递到左节点时,不可以直接maketree(root->left,....),因为root的left是nullptr,里面是没有val等属性的,需要new一个新treenode指针,让root的left指向它,这个时候才可以访问val等属性。
TreeNode* tmp = new TreeNode();
cur->left = tmp;
cur->left = maketree(cur->left, new_inorder, new_postorder);
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* maketree(TreeNode* cur, vector<int> inorder, vector<int> postorder){
//
// cout<<"---------------------\n";
// cout<<"in: ";
// for(auto i:inorder){
// cout<<i<<" ";
// }
// cout<<"\n";
// cout<<"post: ";
// for(auto p:postorder){
// cout<<p<<" ";
// }
// cout<<'\n';
//
int len_p = postorder.size();
// cout<<"postorder"<<postorder.size()<<endl;
int len_i = inorder.size();
cur->val = postorder[len_p-1];
// cout<<"cur-val"<<cur->val<<endl;
int tar = cur->val;
for(int i = 0 ; i < len_i;i++){
if(inorder[i] == tar){
tar = i;
break;
}
}
cout<<"tar: "<<tar<<endl;
if(tar-1>=0){
vector<int> new_inorder(inorder.begin(), inorder.begin()+tar);
vector<int> new_postorder(postorder.begin(), postorder.begin()+tar);
// cout<<"left_in: ";
// for(auto i:new_inorder){
// cout<<i<<" ";
// }
// cout<<"\n";
// cout<<"left_post: ";
// for(auto p:new_postorder){
// cout<<p<<" ";
// }
// cout<<'\n';
TreeNode* tmp = new TreeNode();
cur->left = tmp;
cur->left = maketree(cur->left, new_inorder, new_postorder);
}
if(tar+1<=len_i-1){
vector<int> new_inorder(inorder.begin()+tar+1, inorder.end());
vector<int> new_postorder(postorder.begin()+tar, postorder.end()-1);
// cout<<"right_in: ";
// for(auto i:new_inorder){
// cout<<i<<" ";
// }
// cout<<"\n";
// cout<<"right_post: ";
// for(auto p:new_postorder){
// cout<<p<<" ";
// }
// cout<<'\n';
TreeNode* tmp = new TreeNode();
cur->right = tmp;
cur->right = maketree(cur->right, new_inorder, new_postorder);
}
return cur;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
TreeNode * root = new TreeNode();
return maketree(root,inorder,postorder);
}
};
不创建新数组
```c
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* maketree(TreeNode* cur, vector<int>& inorder, vector<int> &postorder, int i_l, int i_r, int p_l, int p_r){
// cout<<"---------------------\n";
// cout<<"in: ";
// for(int i = i_l; i <= i_r;i++){
// cout<<inorder[i]<<" ";
// }
// cout<<"\n";
// cout<<"post: ";
// for(int i = p_l; i<= p_r;i++){
// cout<<postorder[i]<<" ";
// }
// cout<<'\n';
cur->val = postorder[p_r];
cout<<"cur-val"<<cur->val<<endl;
int tar = cur->val;
for(int i = i_l ; i <= i_r; i++){
if(inorder[i] == tar){
tar = i-i_l;
break;
}
}
cout<<"tar: "<<tar<<endl;
if(i_l+tar-1>=i_l){
// i_l= i_l;
// i_r = i_l + tar -1;
// p_l = p_l;
// p_r = p_l+ tar -1;
// vector<int> new_inorder(inorder.begin(), inorder.begin()+tar);
// vector<int> new_postorder(postorder.begin(), postorder.begin()+tar);
// cout<<"left_in: ";
// for(int i = i_l; i <= i_r;i++){
// cout<<inorder[i]<<" ";
// }
// cout<<"\n";
// cout<<"left_post: ";
// for(int i = p_l; i<= p_r;i++){
// cout<<postorder[i]<<" ";
// }
// cout<<'\n';
cout<<i_l<<" "<<tar -1<<" "<< p_l<<" "<<tar -1<<endl;
TreeNode* tmp = new TreeNode();
cur->left = tmp;
cur->left = maketree(cur->left, inorder, postorder, i_l, i_l + tar -1, p_l, p_l + tar -1);
}
if(i_l+tar+1<=i_r){
// i_l = i_l+tar+1;
// i_r = i_r;
// p_l = p_l+tar;
// p_r = p_r-1;
// vector<int> new_inorder(inorder.begin()+tar+1, inorder.end());
// vector<int> new_postorder(postorder.begin()+tar, postorder.end()-1);
// cout<<"right_in: ";
// for(int i = i_l; i <= i_r;i++){
// cout<<inorder[i]<<" ";
// }
// cout<<"\n";
// cout<<"right_post: ";
// for(int i = p_l; i<= p_r;i++){
// cout<<postorder[i]<<" ";
// }
// cout<<'\n';
cout<< tar+1<<" "<<i_r<< " " <<tar<<" "<<p_r-1<<endl;
TreeNode* tmp = new TreeNode();
cur->right = tmp;
cur->right = maketree(cur->right, inorder, postorder, i_l+tar+1, i_r, p_l+tar, p_r-1);
}
return cur;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
TreeNode * root = new TreeNode();
int i_l=0, i_r=inorder.size()-1, p_l=0, p_r=inorder.size()-1;
return maketree(root,inorder,postorder,i_l,i_r,p_l,p_r);
}
};
最大二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode * makemax(TreeNode* cur, vector<int>& nums, int l, int r){
int gap = l;
for(int i =l ;i<= r;i++){
if(nums[i]> nums[gap]) gap = i;
}
gap-= l;
cout<<"gap: "<<gap<<"l: "<<l<<"r: "<<r<<endl;
cur->val = nums[l+gap];
if(l+gap-1 >= l){
TreeNode* left_tmp = new TreeNode();
cur->left = left_tmp;
cur->left = makemax(cur->left, nums, l, l+gap -1);
}
if(l+gap+1 <= r){
TreeNode* right_tmp = new TreeNode();
cur->right = right_tmp;
cur->right = makemax(cur->right, nums, l+gap+1, r);
}
return cur;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
TreeNode * root = new TreeNode();
return makemax(root, nums, 0, nums.size()-1);
}
};
合并二叉树
此题非常重要的一点是,要想明白不用两棵树都遍历到底,比如下面的例子


只要遍历完第一棵树,即可,后面的节点是直接指向第二棵树的原节点,所以不用遍历了,因为原节点已经指向了后续的节点
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* bfs(TreeNode*cur1, TreeNode*cur2){
if(cur1 == nullptr) return cur2;
if(cur2 == nullptr) return cur1;
TreeNode * cur = new TreeNode();
cur->val = cur1->val + cur2->val;
cur->left = bfs(cur1->left,cur2->left);
cur->right = bfs(cur1->right, cur2->right);
return cur;
}
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
return bfs(root1, root2);
}
};
二叉搜索树搜值
递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* bfs(TreeNode*cur, int val){
if(cur == nullptr) return nullptr;
if(val == cur->val) return cur;
if(val> cur->val) return bfs(cur->right, val);
else return bfs(cur->left, val);
}
TreeNode* searchBST(TreeNode* root, int val) {
return bfs(root,val);
}
};
迭代
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
stack<TreeNode*> st;
if(root == nullptr) return root;
st.push(root);
while(!st.empty()){
TreeNode * tmp = st.top();st.pop();
if(tmp->val == val) return tmp;
if(val < tmp->val && tmp->left) st.push(tmp->left);
if(val > tmp->val && tmp->right) st.push(tmp->right);
}
return nullptr;
}
};
验证二叉搜索树
二叉树是否为二叉搜索数 <==> 中序遍历数组是否单调递增
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool m_travel(TreeNode* cur, long &now){
if(cur == nullptr) return true;
bool l = true;
if(cur->left) l = m_travel(cur->left, now);
cout<<"now"<<now<<endl;
bool m = true;
if(cur->val <= now) {
m = false;
};
now = cur->val;
cout<<"now"<<now<<endl;
bool r =true;
if(cur->right) r= m_travel(cur->right, now);
return l && m && r;
}
bool isValidBST(TreeNode* root) {
if(root == nullptr) return true;
long now = (long)INT32_MIN -1;
return m_travel(root, now);
}
};
二叉搜索树的最小绝对差
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> arr;
void m_travel(TreeNode* cur){
if(cur == nullptr) return;
m_travel(cur->left);
arr.push_back(cur->val);
m_travel(cur->right);
}
int getMinimumDifference(TreeNode* root) {
m_travel(root);
int gap = INT32_MAX;
for(int i = 0; i<arr.size()-1;i++){
int tmp = arr[i]>arr[i+1]?arr[i]-arr[i+1]:arr[i+1]-arr[i];
if(tmp < gap) gap = tmp;
}
return gap;
}
};
.二叉搜索树中的众数
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_map<int, int> map;
void m_travel(TreeNode* cur){
if(cur == nullptr) return;
m_travel(cur->left);
map[cur->val]++;
m_travel(cur->right);
}
vector<int> findMode(TreeNode* root) {
int max = 0;
m_travel(root);
for(auto item:map){
if(item.second > max) max = item.second;
}
vector<int> res;
for(auto item:map){
if(item.second == max) res.push_back(item.first);
}
return res;
}
};
二叉树的最近公共祖先
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* b_travel(TreeNode*cur, TreeNode*p, TreeNode*q){
if(cur == nullptr || cur == p || cur == q) return cur;
TreeNode * l = b_travel(cur->left, p,q);
TreeNode* r = b_travel(cur->right,p ,q);
if(l && r) return cur;
if(l && !r) return l;
if(!l && r) return r;
return nullptr;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return b_travel(root,p,q);
}
};
二叉搜索树最近公共祖先
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* b_travel(TreeNode *cur,TreeNode* p, TreeNode* q){
if(p->val > cur->val && q->val > cur->val) return b_travel(cur->right,p,q);
if(p->val < cur->val && q->val < cur->val) return b_travel(cur->left,p,q);
return cur;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return b_travel(root,p,q);
}
};
二叉搜索树中的插入操作
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr) return new TreeNode(val);
TreeNode * pre = new TreeNode();
TreeNode * cur = root;
while(cur){
pre = cur;
if(val > cur->val) cur = cur->right;
else if(val < cur->val) cur = cur->left;
}
TreeNode *tmp = new TreeNode();
tmp->val = val;
if(pre->val > val) pre->left = tmp;
else pre -> right = tmp;
return root;
}
};
删除二叉搜索树中的节点
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* f_travel(TreeNode* cur, int val){
if(cur == nullptr) return cur;
if(cur->val == val){
if(!cur->left && !cur->right){
delete cur;
return nullptr;
}
else if(!cur->left && cur->right){
TreeNode * tmp = cur->right;
delete cur;
return tmp;
}
else if(cur->left && !cur->right){
TreeNode*tmp = cur->left;
delete cur;
return tmp;
}
else{
TreeNode * rr = cur->right;
TreeNode* tmp = cur->right;
while(tmp->left) tmp = tmp->left;
tmp->left = cur->left;
delete cur;
return rr;
}
}
if(cur->val > val) cur->left = f_travel(cur->left,val);
if(cur->val< val) cur->right = f_travel(cur->right,val);
return cur;
}
TreeNode* deleteNode(TreeNode* root, int key) {
return f_travel(root,key);
}
};
修剪二叉搜索树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* bfs(TreeNode* cur, int low ,int high){
if(cur == nullptr) return nullptr;
if(cur->val < low){
return bfs(cur->right, low, high);
}
else if(cur->val > high){
return bfs(cur->left, low, high);
}
cur->left = bfs(cur->left, low ,high);
cur->right = bfs(cur->right,low,high);
return cur;
}
TreeNode* trimBST(TreeNode* root, int low, int high) {
return bfs(root,low,high);
}
};
将有序数组转换为二叉搜索树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* maketree(TreeNode* cur, int left, int right, vector<int>& nums){
int mid = 0;
if(right>=left) {
mid = left + (right-left)/2;
cur->val = nums[mid];
}
else return nullptr;
TreeNode* tmp1 = new TreeNode();
TreeNode* tmp2 = new TreeNode();
cur->left = maketree(tmp1, left, mid - 1,nums);
cur->right = maketree(tmp2, mid+1 ,right, nums);
return cur;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
TreeNode* root = new TreeNode();
return maketree(root, 0, nums.size()-1, nums);
}
};
把二叉搜索树转换为累加树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void bfs(TreeNode* cur, int& pre){
if(cur ==nullptr) return;
bfs(cur->right, pre);
cur->val += pre;
pre = cur->val;
bfs(cur->left, pre);
return;
}
TreeNode* convertBST(TreeNode* root) {
int pre = 0;
bfs(root, pre);
return root;
}
};

浙公网安备 33010602011771号