144. Binary Tree Preorder Traversal

82人阅读 评论(0)

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

For example:
Given binary tree [1,null,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> s;
preorderTraversal(root, s);
return s;
}
void preorderTraversal(TreeNode *root, vector<int> &s) {
if (root != NULL) {
s.push_back(root -> val);
preorderTraversal(root -> left, s);
preorderTraversal(root -> right, s);
}
}
};

/**
* 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) {
stack<TreeNode *> s;
vector<int> visit;
TreeNode *pointer = root;
s.push(NULL);
while (pointer) {
visit.push_back(pointer -> val);
if (pointer -> right != NULL) {
s.push(pointer -> right);
}
if (pointer -> left != NULL) {
pointer = pointer -> left;
} else {
pointer = s.top();
s.pop();
}
}
return visit;
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：4954次
• 积分：1001
• 等级：
• 排名：千里之外
• 原创：97篇
• 转载：0篇
• 译文：0篇
• 评论：0条
阅读排行