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