您的位置:首页 > 其它

leetcode-94-Binary Tree Inorder Traversal

2015-06-21 23:08 471 查看


Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.

For example:

Given binary tree
{1,#,2,3}
,

1
\
2
/
3


return
[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>v;
v.clear();
stack<TreeNode*>s;
TreeNode* x;
s.push(root);
if(!root) return v;

while(!s.empty()){
x=s.top();
v.push_back(x->val);
s.pop();

if(x->right) s.push(x->right);
if(x->left) s.push(x->left);
}
return v;
}
};

class Solution { //先序遍历  递归
public:
vector<int>v;
vector<int> preorderTraversal(TreeNode* root) {
v.clear();
if(!root) return v;
pre(root);
return v;
}
void pre(TreeNode* p){
if(!p) return;
v.push_back(p->val);
pre(p->left);
pre(p->right);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: