结果
- 使用迭代算法
- 解题思路:Morris遍历 利用结点空指针
/**
* 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) {
vector<int> ans;
while (root) {
if (nullptr == root->left) {
ans.emplace_back(root->val);
root = root->right;
} else {
//先找到前驱节点
TreeNode* pre = root->left;
while (pre->right && pre->right != root) { //第一次找到前驱节点
pre = pre->right;
}
if (nullptr == pre->right) {
pre->right = root; //第一次来,添加回溯指针
ans.emplace_back(root->val);
root = root->left;
} else { //第二次来 已处理完左子树
pre->right = nullptr;//还原树的结构
root = root->right;
}
}
}
return ans;
}
};
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)