您的位置:首页 > 其它

Leetcode: Binary Tree Preorder Traversal

2013-12-25 23:59 253 查看
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]
.

Note: Recursive solution is trivial, could you do it iteratively?

过不了的方法,空间复杂度:

class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> result;
if (root == NULL) {
return result;
}

TreeNode *node = NULL;
stack<TreeNode*> stack_tree;
stack_tree.push(root);
while (!stack_tree.empty()) {
node = stack_tree.top();
stack_tree.pop();
result.push_back(node->val);
if (root->right != NULL) {
stack_tree.push(root->right);
}
if (root->left != NULL) {
stack_tree.push(root->left);
}
}

return result;
}
};


可以的:

/**
* Definition for binary tree
* 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> result;
stack<TreeNode*> stack_tree;
while (root != NULL || !stack_tree.empty()) {
while (root != NULL) {
result.push_back(root->val);
stack_tree.push(root);
root = root->left;
}
if (!stack_tree.empty()) {
root = stack_tree.top();
root = root->right;
stack_tree.pop();
}
}

return result;
}
};


=========================第二次============================

标准的解法:

/**
* Definition for binary tree
* 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> result;
stack<TreeNode*> nodes;
while (root != NULL || !nodes.empty()) {
while (root != NULL) {
result.push_back(root->val);
nodes.push(root);
root = root->left;
}

if (!nodes.empty()) {
root = nodes.top();
nodes.pop();
root = root->right;
}
}

return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 二叉树 遍历