题目描述
Given a binary tree, return the inorder traversal of its nodes’ values.
Example:
Input: [1,null,2,3]
1
2
/
3
Output: [1,3,2]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码
区别与教科书的非递归写法。
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// My Non-Recursive
// Time Complexity: O(n), n is the node number in the tree
// Space Complexity: O(h), h is the height of the tree
class Solution {
private:
struct Command{
string s; // go, print
TreeNode* node;
Command(string s, TreeNode* node): s(s), node(node){}
};
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if( root == NULL )
return res;
stack<Command> stack;
stack.push(Command("go", root));
while( !stack.empty() ){
Command command = stack.top();
stack.pop();
if(command.s == "print")
res.push_back(command.node->val);
else{
assert(command.s == "go");
if(command.node->right)
stack.push(Command("go",command.node->right));
stack.push(Command("print", command.node));
if(command.node->left)
stack.push(Command("go",command.node->left));
}
}
return res;
}
};
int main() {
return 0;
}
经典非递归
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// Classic Non-Recursive algorithm for inorder traversal
// Time Complexity: O(n), n is the node number in the tree
// Space Complexity: O(h), h is the height of the tree
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if( root == NULL )
return res;
stack<TreeNode*> stack;
TreeNode* cur = root;
while(cur != NULL || !stack.empty()){
while(cur != NULL){
stack.push(cur);
cur = cur->left;
}
cur = stack.top();
stack.pop();
res.push_back(cur->val);
cur = cur->right;
}
return res;
}
};
int main() {
return 0;
}