给定一个二叉树,返回它的 前序 遍历。
一、思路
递归法就不必说了,直接上非递归。
利用栈的特点,依次保存右孩子、左孩子。
C++代码:
class Solution {
public:
vector<int> ans;
vector<int> preorderTraversal(TreeNode* root) {
if (!root)
return ans;
stack<TreeNode *> list;
list.push(root);
while (!list.empty()) {
int len = list.size();
TreeNode *temp = list.top();
list.pop();
ans.push_back(temp->val);
if (temp->right)
list.push(temp->right);
if (temp->left)
list.push(temp->left);
}
return ans;
}
};