LeetCode144:Binary Tree Preorder Traversal
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;
}
};