Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
62 lines (60 sloc) 1.26 KB
/*
* @lc app=leetcode.cn id=144 lang=cpp
*
* [144] 二叉树的前序遍历
*
* https://leetcode-cn.com/problems/binary-tree-preorder-traversal/description/
*
* algorithms
* Medium (56.22%)
* Total Accepted: 13.3K
* Total Submissions: 23.5K
* Testcase Example: '[1,null,2,3]'
*
* 给定一个二叉树,返回它的 前序 遍历。
*
* 示例:
*
* 输入: [1,null,2,3]
* ⁠ 1
* ⁠ \
* ⁠ 2
* ⁠ /
* ⁠ 3
*
* 输出: [1,2,3]
*
*
* 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//迭代+栈
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ret;
stack<TreeNode*> stack;
TreeNode* curNode=root;
while(curNode || !stack.empty())
{
while(curNode){
stack.push(curNode);
ret.push_back(curNode->val);
curNode=curNode->left;
}
curNode=stack.top();
curNode=curNode->right;
stack.pop();
}
return ret;
}
};
You can’t perform that action at this time.