Given a binary tree, return the preorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
先序遍历应该是三种遍历方式中最好使用非递归来实现的了。
可以每次访问一个节点后再将其右子节点入栈,然后左子节点入栈。然后再从栈中取元素,可以发现就是先序遍历的结果。需要注意的是如果子节点不存在就不需要进行入栈操作。
runtime:4ms
/**
* 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> res;
if(root==NULL)
return res;
stack<TreeNode *> s;
TreeNode * node=root;
s.push(node);
while(!s.empty())
{
node=s.top();
s.pop();
res.push_back(node->val);
if(node->right) s.push(node->right);
if(node->left) s.push(node->left);
}
return res;
}
};