给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
方法见博客:
leetcode144二叉树前序遍历
struct Command{
string s;
TreeNode* node;
Command(string s, TreeNode* node) : s(s), node(node) {}
};
class Solution {
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;
}
};