c_cpp 94.二叉树Inorder遍历
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 94.二叉树Inorder遍历相关的知识,希望对你有一定的参考价值。
//Runtime: 0 ms, faster than 100.00%
#include <ios>
static auto fastInput = []() {
ios_base::sync_with_stdio(false),cin.tie(nullptr);
return 0;
}();
class Solution {
public:
vector<int> array;
vector<int> inorderTraversal(TreeNode* root) {
travelTree(root);
return array;
}
void travelTree(TreeNode* root){
if(root){
travelTree(root->left);
array.push_back(root->val);
travelTree(root->right);
}
}
};
//Runtime: 0 ms, faster than 100.00%
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> nodes;
stack<TreeNode*> todo;
TreeNode* cur = root;
while(cur || !todo.empty()){
if(cur){
todo.push(cur);
cur = cur->left;
}
else{
cur = todo.top();
todo.pop();
nodes.push_back(cur->val);
cur = cur->right;
}
}
return nodes;
}
};
//Runtime: 0 ms, faster than 100.00%
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
TreeNode* cur = root;
vector<int> nodes;
while(cur){
if(cur->left){
TreeNode* pre = cur->left;
while(pre->right && (pre->right != cur))
pre = pre->right;
if(!(pre->right)){
pre->right = cur;
cur = cur->left;
}
else{
pre->right = NULL;
nodes.push_back(cur->val);
cur = cur->right;
}
}
else{
nodes.push_back(cur->val);
cur = cur->right;
}
}
return nodes;
}
};
以上是关于c_cpp 94.二叉树Inorder遍历的主要内容,如果未能解决你的问题,请参考以下文章
算法: 二叉树中序遍历94. Binary Tree Inorder Traversal
算法:中序遍历二叉树94. Binary Tree Inorder Traversal
c_cpp 从inorder和postorder遍历构造二叉树
94. Binary Tree Inorder Traversal(非递归实现二叉树的中序遍历)
leetCode 94.Binary Tree Inorder Traversal(二叉树中序遍历) 解题思路和方法
leetcode 94.Binary Tree Inorder Traversal 二叉树的中序遍历