标签:line 不为 rsa img 合并 init ref lse struct
定义一个存放树中数据的向量 data,从根节点开始,如果节点不为空,那么
/**
* 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:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> data = {};
vector<int> temp = {};
if (root != NULL)
{
temp = inorderTraversal(root->left);
data.insert(data.end(),temp.begin(),temp.end());
data.push_back(root->val);
temp = inorderTraversal(root->right);
data.insert(data.end(),temp.begin(),temp.end());
}
return data;
}
};
定义一个存放树中节点的栈 node_stack 和存放数据的向量 data,从根节点开始,如果节点不为空或者栈非空,循环以下过程:
/**
* 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:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> data = {};
stack<TreeNode*> node_stack;
TreeNode* temp = root;
while (temp || !node_stack.empty())
{
while(temp != NULL)
{
node_stack.push(temp);
temp = temp->left;
}
temp = node_stack.top();
node_stack.pop();
data.push_back(temp->val);
temp = temp->right;
}
return data;
}
};
前面两种方法要么需要函数栈要么需要人工栈,其空间复杂度为 \(O(n)\),而 Morris 遍历法可以做到在不影响时间复杂度的情况下做到空间复杂度为 \(O(1)\)。
定义一个存放数据的向量 data,从根节点开始,如果当前节点非空,循环以下过程:
/**
* 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:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> data = {};
TreeNode* cur = root;
TreeNode* pre = NULL;
while (cur)
{
if (cur->left == NULL)
{
data.push_back(cur->val);
cur = cur->right;
}
else
{
// 寻找前驱结点
pre = cur->left;
while (pre->right != cur && pre->right)
{
pre = pre->right;
}
if (pre->right == NULL)
{
pre->right = cur;
cur = cur->left;
}
else
{
data.push_back(cur->val);
cur = cur->right;
pre->right = NULL;
}
}
}
return data;
}
};
获取更多精彩,请关注「seniusen」!
标签:line 不为 rsa img 合并 init ref lse struct
原文地址:https://www.cnblogs.com/seniusen/p/9973619.html