您的位置:首页 > 其它

Binary Tree Preorder Traversal

2018-04-01 18:25 323 查看
Given a binary tree, return the preorder traversal of its nodes' values.
Example
Given:
1
/ \
2   3
/ \
4   5
return 
[1,2,4,5,3]
.class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL)
return res;
stack<TreeNode*> s;
s.push(root);
while(!s.empty()){
TreeNode *t=s.top();
s.pop();
v.push_back(t->val);
if(t->right) //因为栈是先进后出,所以先放入右结点
s.push(t->right);
if(t->left)
s.push(t->left);
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: