题目要求:
给定一个二叉树的根节点 root ,返回它的 中序 遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:输入:root = []
输出:[]
示例 3:输入:root = [1]
输出:[1]
示例 4:输入:root = [1,2]
输出:[2,1]
示例 5:输入:root = [1,null,2]
输出:[1,2]
提示:树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
进阶: 递归算法很简单,你可以通过迭代算法完成吗?来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
解题代码:
//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) {} }; struct Command { string s; // go, print 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; } };