- 单值二叉树
如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。
只有给定的树是单值二叉树时,才返回 true;否则返回 false。
示例 1:
输入:[1,1,1,1,1,null,1]
输出:true
示例 2:
输入:[2,2,2,5,2]
输出:false
/**
* 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 isUnivalTreeHelp(TreeNode * root, int val)
{
if (!root)
return true;
return root->val == val &&
isUnivalTreeHelp(root->left, val) &&
isUnivalTreeHelp(root->right, val);
}
bool isUnivalTree(TreeNode* root) {
if (!(root->left) && !(root->right))
return true;
int value = root->val;
return isUnivalTreeHelp(root, value);
}
};
- 二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回它的最大深度 3 。
链接
/**
* 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) {
if(!root)
return 0;
if (!(root->left) && !(root->right))
return 1;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
- 翻转二叉树
翻转一棵二叉树。
示例:
链接
/**
* 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 invertTreeHeaper(TreeNode * root)
{
if (!root) //必须有
return;
if (!(root->left) && !(root->right))
return;
//处理根
TreeNode * tmp = root->left;
root->left = root->right;
root->right = tmp;
invertTreeHeaper(root->left);
invertTreeHeaper(root->right);
}
TreeNode* invertTree(TreeNode* root) {
if (!root)
return NULL;
if (!(root->left) && !(root->right))
return root;
invertTreeHeaper(root);
return 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:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (!p && !q)
return true;
if (!p || !q)
return false;
return p->val == q->val &&
isSameTree(p->left, q->left)&&
isSameTree(p->right, q->right);
}
};
- 对称二叉树
给定一个二叉树,检查它是否是镜像对称的。
链接
/**
* 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 isSymmetricHelper(TreeNode * root1, TreeNode * root2)
{
if (!root1 && !root2)
return true;
if (!root1 || !root2)
return false;
return root1->val == root2->val &&
isSymmetricHelper(root1->left, root2->right)&&
isSymmetricHelper(root1->right, root2->left);
}
bool isSymmetric(TreeNode* root) {
if (!root)
return true;
if (!(root->left) && !(root->right))
return true;
TreeNode * tmp = root;
return isSymmetricHelper(root, tmp);
}
};
- 二叉树的前序遍历
链接
递归
/**
* 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 preorderTraversalHeaper(TreeNode * root, vector<int> & res)
{
if (!root)
return ;
res.push_back(root->val);
preorderTraversalHeaper(root->left, res);
preorderTraversalHeaper(root->right, res);
}
vector<int> preorderTraversal(TreeNode* root) {
if (!root)
return {};
vector<int> res;
preorderTraversalHeaper(root, res);
return res;
}
};
非递归
vector<int> preorderTraversal(TreeNode* root) {
//非递归
vector<int> res;
stack<TreeNode*> st;
TreeNode* cur = root;
while (cur || !st.empty())
{
while (cur)
{
//访问根
res.push_back(cur->val);
st.push(cur);
cur = cur->left;
}
TreeNode* tmp = st.top();
st.pop();
cur = tmp->right;//指向右节点
}
return res;
}
- 二叉树的中序遍历
给定一个二叉树的根节点 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:
void inorderTraversalHeaper(TreeNode * root, vector<int> & res)
{
if (!root)
return;
inorderTraversalHeaper(root->left, res);
res.push_back(root->val);
inorderTraversalHeaper(root->right, res);
}
vector<int> inorderTraversal(TreeNode* root) {
if (!root)
return {};
vector<int> res;
inorderTraversalHeaper(root, res);
return res;
}
};
非递归
vector<int> inorderTraversal(TreeNode* root) {
//非递归
vector<int> res;
stack<TreeNode*> st;
TreeNode* cur = root;
while (cur || !st.empty())
{
while (cur)
{
st.push(cur);
cur = cur->left;
}
TreeNode* tmp = st.top();//最左结点
st.pop();
res.push_back(tmp->val);
cur = 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:
void postorderTraversalHelper(TreeNode * root, vector<int> & res)
{
if (!root)
return;
postorderTraversalHelper(root->left, res);
postorderTraversalHelper(root->right, res);
res.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
if (!root)
return {};
vector<int> res;
postorderTraversalHelper(root, res);
return res;
}
};
非递归
vector<int> postorderTraversal(TreeNode* root) {
//非递归
vector<int> res;
stack<TreeNode*> st;
TreeNode* pre = nullptr;
TreeNode* cur = root;
while (cur || !st.empty())
{
while (cur)
{
st.push(cur);
cur = cur->left;
}
TreeNode* tmp = st.top();
//最左结点的右节点为空或已访问过
if (tmp->right == nullptr || tmp->right == pre)
{
pre = tmp;//更新pre
st.pop();
res.push_back(tmp->val);
}
//访问右节点
else
{
cur = tmp->right;//指向右节点
}
}
return res;
}
- 二叉树的层序遍历
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3
9 20
15 7
返回其层序遍历结果:
[
[3],
[9,20],
[15,7]
]
链接
/**
* 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>> levelOrder(TreeNode* root) {
if (!root)
return {};
queue<TreeNode*> qu;
vector< vector<int> > result;
qu.push(root);
while (!qu.empty())
{
vector<int> v;
int size = qu.size();
for (int i = 0; i < size; i++)
{
TreeNode * node = qu.front();
v.push_back(node->val);
qu.pop();
if (node->left)
qu.push(node->left);
if (node->right)
qu.push(node->right);
}
result.push_back(v);
}
return result;
}
};
/**
* 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:
//之字形打印二叉树
void levelOrderHelp(TreeNode * root, vector< vector<int> > & res)
{
bool flag = false;
queue<TreeNode*> q;
q.push(root);
while (!q.empty())
{
int size = q.size();
vector<int> v(size);
for (int i = 0; i < size; i++)
{
TreeNode * tmp = q.front();
q.pop();
//奇数从左往右 偶数从右往左
v[flag ? size-1-i: i] = tmp->val;
if (tmp->left)
{
q.push(tmp->left);
}
if (tmp->right)
{
q.push(tmp->right);
}
}
flag = !flag;
res.push_back(v);
v.clear();
}
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector< vector<int> > res;
if (!root)
return {};
levelOrderHelp(root, res);
return res;
}
};
- 另一棵树的子树
给你两棵二叉树 root 和 subRoot 。检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。如果存在,返回 true ;否则,返回 false 。
二叉树 tree 的一棵子树包括 tree 的某个节点和这个节点的所有后代节点。tree 也可以看做它自身的一棵子树。
链接
/**
* 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 isSameStructure(TreeNode * root1, TreeNode * root2)
{
if (!root1 && !root2)
return true;
if (!root1 || !root2)
return false;
return root1->val == root2->val &&
isSameStructure(root1->left, root2->left)&&
isSameStructure(root1->right, root2->right);
}
bool isSubtreeHelper(TreeNode * root, TreeNode * subRoot)
{
if (!root)
return false;
return isSameStructure(root, subRoot) ||
isSubtreeHelper(root->left, subRoot) ||
isSubtreeHelper(root->right, subRoot);
}
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
return isSubtreeHelper(root, subRoot);
}
};
链接
注: 树的子树和子结构不一样
这种即为子结构.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
typedef struct TreeNode TreeNode;
bool isSameStructure(TreeNode * root1, TreeNode * root2)
{
if (!root2)
return true;
if (!root1)
return false;
return root1->val == root2->val &&
isSameStructure(root1->left, root2->left)&&
isSameStructure(root1->right, root2->right);
}
bool isSubStructureHelper(struct TreeNode* root, struct TreeNode* subRoot){
if (!root)
return false;
return isSameStructure(root, subRoot) ||
isSubStructureHelper(root->left, subRoot) ||
isSubStructureHelper(root->right, subRoot);
}
bool isSubStructure(TreeNode * root, TreeNode * subRoot)
{
if (!subRoot)
return false;
return isSubStructureHelper(root, subRoot);
KY11 二叉树遍历
编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。
输入描述:
输入包括1行字符串,长度不超过100。
输出描述:
可能有多组测试数据,对于每组数据, 输出将输入字符串建立二叉树后中序遍历的序列,每个字符后面都有一个空格。 每个输出结果占一行。
示例1
输入:
abc##de#g##f###
复制
输出:
c b e g d f a
链接
#include<stdio.h>
#include<malloc.h>
#include<assert.h>
#include<string.h>
typedef struct Node
{
char ch;
struct Node * left;
struct Node * right;
}Node;
Node * BuyOneNode()
{
Node * node = (Node *)malloc(sizeof(Node));
if (!node)
{
assert(0);
return NULL;
}
node->left = node->right = NULL;
return node;
}
void InOrderTraver(Node * root)
{
if (!root)
return;
InOrderTraver(root->left);
printf("%c ", root->ch);
InOrderTraver(root->right);
}
Node * CreateBitNode(char str[], int *index,int len, char invalid)
{
if (*index < len && str[*index] != invalid)
{
Node * root = BuyOneNode();
root->ch = str[*index];
*index += 1;
root->left = CreateBitNode(str, index, len, invalid);
*index += 1;
root->right = CreateBitNode(str, index, len, invalid);
return root;
}
return NULL;
}
void DestroyBitNode(Node ** root)
{
if (!(*root))
return;
DestroyBitNode(&(*root)->left);
DestroyBitNode(&(*root)->right);
free(*root);
*root = NULL;
}
int main()
{
char str[100];
while (scanf("%s", str) != EOF)
{
int len = strlen(str);
int index = 0;
Node * root = CreateBitNode(str, &index, len, '#');
InOrderTraver(root);
printf("\n");
DestroyBitNode(&root);
}
return 0;
}
判断是否为完全二叉树
链接
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
typedef struct TreeNode TreeNode;
TreeNode * ConstructCore(int * startPreorder, int * endPreorder, int * startInorder, int * endInorder)
{
int rootValue = startPreorder[0];
TreeNode * root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = rootValue;
root->left = root->right = NULL;
//当前只有一个结点
if (startPreorder == endPreorder)
{
if (startInorder == endInorder)
return root;
}
int * rootInorder = startInorder;
//找到根节点在中序遍历的位置
while (rootInorder < endInorder && *rootInorder != rootValue)
{
++rootInorder;
}
int leftLength = rootInorder - startInorder; //个数
int * leftPreorderEnd = startPreorder+leftLength;
if (leftLength > 0) //大于0
{
root->left = ConstructCore(startPreorder+1, leftPreorderEnd, startInorder, rootInorder-1);
}
if (leftLength < endPreorder - startPreorder) //不越界
{
root->right = ConstructCore(leftPreorderEnd+1,endPreorder,rootInorder+1, endInorder);
}
return root;
}
TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize){
if (!preorder || !inorder || inorderSize <= 0)
return 0;
return ConstructCore(preorder, preorder+inorderSize-1, inorder, inorder+inorderSize-1);
}
二叉搜索树的最近公共祖先
链接
**解析:**二叉搜索树的特性是中序遍历为一个有序序列.
方法一:
依次从根节点开始分别寻找一条到p和q的路径,然后把各自路径经过的结点值保存在两个数组中,然后对两个数组依次遍历,它们第一个相等的值即为最近的公共祖先.
方法二:
如果p和q结点的值都小于当前根节点的值,就去该根节点的右子树中寻找;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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode * ancestor = root;
while (true)
{
//小于
if (p->val < ancestor->val && q->val < ancestor->val)
{
ancestor = ancestor->left;
}
//但与
else if (p->val > ancestor->val && q->val > ancestor->val)
{
ancestor = ancestor->right;
}
//当前结点即为所求
else{
break;
}
}
return ancestor;
}
};
二叉树的最近公共祖先(上题为二叉搜索树)
添加链接描述
解析:
方法一:
需要借助临时变量unordered_map<int, TreeNode*> fa来存储二叉树中每个结点的父节点和unordered_map<int, bool> vis来记录当前结点是否被访问过.
然后,我们让p结点向上遍历,修改访问状态为已访问,直至遇到空结点
最后,让q结点向上遍历,遇到访问状态为已访问的,我们就找到答案了.
方法二:
利用递归的思想
//方法一
class Solution {
public:
//临时变量存储父节点
unordered_map<int, TreeNode*> fa;
//记录状态
unordered_map<int, bool> vis;
void dfs(TreeNode * root)
{
if (root->left)
{
fa[root->left->val] = root;
dfs(root->left);
}
if (root->right)
{
fa[root->right->val] = root;
dfs(root->right);
}
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!p && !q)
return root;
fa[root->val] = NULL;//根节点的父节点为NULL
dfs(root);
while (p)
{
vis[p->val] = true;//修改状态
p = fa[p->val];
}
while (q)
{
if (vis[q->val])//被访问 找到目标节点
{
return q;
}
q = fa[q->val];
}
return NULL;
}
};
//方法二
class Solution {
public:
TreeNode * ans;
bool dfs(TreeNode * root, TreeNode * p, TreeNode * q)
{
if (!root)
{
return false;
}
//左子树是否包含p或q
bool lson = dfs(root->left, p, q);
//右子树是否有p或q
bool rson = dfs(root->right, p, q);
if ((lson && rson) || ((root->val == p->val || root->val == q->val) && (lson || rson)))
{
ans = root;
}
return lson || rson || (root->val == p->val || root->val == q->val);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!p && !q)
return root;
dfs(root, p, q);
return ans;
}
};
//方法三
class Solution {
public:
bool FindPath(TreeNode* root, TreeNode* t, stack<TreeNode*>& path)//寻找root到t的路径
{
if (!root)
{
return false;
}
path.push(root);
if (root == t)
return true;
if (FindPath(root->left, t, path))
return true;
if (FindPath(root->right, t, path))
return true;
path.pop();
return false;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
stack<TreeNode*> pathP;
stack<TreeNode*> pathQ;
FindPath(root, p, pathP); //获取root到p的路径
FindPath(root, q, pathQ); //获取root到q的路径
stack<TreeNode*> * longPath = &pathP;
stack<TreeNode*> * shortPath = &pathQ;
if (pathP.size() < pathQ.size())
swap(longPath, shortPath);
//让长的先走
while (longPath->size() > shortPath->size())
{
longPath->pop();
}
while (longPath->top() != shortPath->top())
{
longPath->pop();
shortPath->pop();
}
return longPath->top();
// int lenP = pathP.size();
// int lenQ = pathQ.size();
// if (lenP < lenQ)
// {
// swap(lenP,lenQ);
// swap(pathP, pathQ);
// }
// for (int i = 0; i < lenP-lenQ; i++)
// {
// pathP.pop();
// }
// while (pathP.top() != pathQ.top())
// {
// pathP.pop();
// pathQ.pop();
// }
// return pathP.top();
}
};
/**
* 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 {
/*//自顶向下递归
int getDepth(TreeNode* root)
{
if (!root)
{
return 0;
}
return max(getDepth(root->left), getDepth(root->right)) + 1;
}/*
/*bool isBalancedHelper(TreeNode* root)
{
return ( abs(getDepth(root->left) - getDepth(root->right)) ) <= 1;
}*/
int height(TreeNode * root)
{
//自底向上递归 减少重复计算树高
if (!root)
return 0;
int left = height(root->left);
int right = height(root->right);
//只要出现一个不平衡 返回值为-1
//若平衡 返回值为树高
if (left == -1 || right == -1 || abs(left-right) > 1)
{
return -1;
}
return max(left,right) + 1;
}
public:
bool isBalanced(TreeNode* root) {
return height(root) >= 0;
}
/*bool isBalanced(TreeNode* root) {
//前序遍历
if (!root)
return true;
//必须要有abs绝对值
return abs(getDepth(root->left)-getDepth(root->right)) <= 1
&& isBalanced(root->left)
&& isBalanced(root->right);
}*/
/*bool isBalanced(TreeNode* root) {
if (!root)
return true;
queue<TreeNode*> q;
q.push(root);
while (!q.empty())
{
TreeNode * tmp = q.front();
q.pop();
if (!isBalancedHelper(tmp))
{
return false;
}
if (tmp->left)
q.push(tmp->left);
if (tmp->right)
q.push(tmp->right);
}
return true;
}*/
};
方法一:
//使用中序遍历
long long pre = LONG_MIN;//
bool isValidBST(TreeNode* root) {
if (!root)
return true;
bool fl = isValidBST(root->left);
if (root->val <= pre)//只要保证root值>pre就行
return false;
pre = root->val; //更新pre
bool fr = isValidBST(root->right);
return fl && fr;
}
方法二:
//要保证二叉搜索树,必须保证左子树所有的结点值<根节点的值,右子树所有的值>根结点的值
//使用long的原因时有个测试样例最小值为[2147483647]值为,先保证root通过,所以要用LONG_MIN
bool isValidBSTHelper(TreeNode * root, long long lower, long long upper) //接收值不能用int
{
if (!root)
return true;
//判断root的值是否符合要求
if (root->val <= lower || root->val >= upper)
return false;
return isValidBSTHelper(root->left, lower, root->val) &&
isValidBSTHelper(root->right, root->val, upper);
}
bool isValidBST(TreeNode* root) {
//return isValidBSTHelper(root, INT_MIN, INT_MAX);
return isValidBSTHelper(root, LONG_MIN, LONG_MAX);
class Solution {
public:
TreeNode * pre = NULL;
TreeNode * root = NULL;
//总体还是中序遍历
TreeNode* Convert(TreeNode* pRootOfTree) {
if (!pRootOfTree)
return NULL;
Convert(pRootOfTree->left);
//保存根节点
if (!root)
root = pRootOfTree;
//改变指向 通过前一结点和当前节点来修改
if (pre)
{
pRootOfTree->left = pre;
pre->right = pRootOfTree;
}
else
pRootOfTree->left = pre;
//更新pre
pre = pRootOfTree;
Convert(pRootOfTree->right);
return root;
}
/*
TreeNode* Convert(TreeNode* pRootOfTree) {
if (!pRootOfTree)
return nullptr;
vector<TreeNode*> v;
//通过中序遍历拿到所有的二叉搜索树结点
inOrder(pRootOfTree, v);
//再通过循环改变指向
for (int i = 0; i < v.size()-1; i++)
{
v[i]->right = v[i+1];
v[i+1]->left = v[i];
}
return v[0];
}
void inOrder(TreeNode * pRootOfTree, vector<TreeNode*> &v)
{
if (!pRootOfTree)
return;
inOrder(pRootOfTree->left, v);
v.push_back(pRootOfTree);
inOrder(pRootOfTree->right, v);
}*/
};
class Solution {
public:
void tree2strHelp(TreeNode*& root, string& res)
{
if (!root)
return;
// res += (root->val + '0');//可能为负数,用to_string()
res += to_string(root->val);
//左不为空 或 左为空,右不为空
if (root->left || root->right)
{
res += "(";
tree2strHelp(root->left, res);
res += ")";
}
if (root->right)
{
res += "(";
tree2strHelp(root->right, res);
res += ")";
}
}
string tree2str(TreeNode* root) {
string res;
tree2strHelp(root, 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:
//必须用引用
//全程使用后续遍历
void mergeTreesHelp(TreeNode*& root1, TreeNode*& root2)
{
if (!root1 && !root2)
return ;
if (!root2)
return;
if (!root1)//出现root1为空 实际为上一次root1->left/right的引用,直接赋值即可
{
root1 = root2;
return;
}
root1->val += root2->val;//普通的值相加到root1的结点上
mergeTreesHelp(root1->left,root2->left);
mergeTreesHelp(root1->right,root2->right);
}
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
mergeTreesHelp(root1, root2);
return root1;
}
};
class Solution {
public:
int maxVal = INT_MIN;
int maxPathSumHelp(TreeNode* root)
{
if (!root)
return 0;
//最小为0
int left = max(maxPathSumHelp(root->left),0);
int right = max(maxPathSumHelp(root->right),0);
maxVal = max(maxVal, root->val+left+right);
return root->val + max(left,right);
}
int maxPathSum(TreeNode* root) {
maxPathSumHelp(root);
return maxVal;
}
};