您的位置:首页 > 其它

lintcode 二叉树的前序遍历

2015-12-07 22:05 239 查看
给出一棵二叉树,返回其节点值的前序遍历。

样例

给出一棵二叉树
{1,#,2,3}
,

返回
[1,2,3]
.

题解1 递归

class Solution {

public:

/**

* @param root: The root of binary tree.

* @return: Preorder in vector which contains node values.

*/

void preorder(TreeNode *root,vector<int>&result) {

if (root == nullptr)return;

result.push_back(root->val);

preorder(root->left,result);

preorder(root->right,result);

}

vector<int> preorderTraversal(TreeNode *root) {

// write your code here

vector<int>result;

preorder(root,result);

return result;

}

};

题解 2 栈

class Solution {

public:

/**

* @param root: The root of binary tree.

* @return: Preorder in vector which contains node values.

*/

vector<int> preorderTraversal(TreeNode *root) {

// write your code here

vector<int>result;

const TreeNode*p = root;

stack<const TreeNode *>s;

if (p != nullptr) s.push(p);

while (!s.empty()){

p = s.top();

s.pop();

result.push_back(p->val);

if(p->right != nullptr)s.push(p->right);

if(p->left != nullptr)s.push(p->left);

}

return result;

}

};

题解3 Morris

class Solution {

public:

/**

* @param root: The root of binary tree.

* @return: Preorder in vector which contains node values.

*/

vector<int> preorderTraversal(TreeNode *root) {

// write your code here

vector<int>result;

TreeNode *p = root, *temp;

while(p != nullptr) {

if(p->left == nullptr) {

result.push_back(p->val);

p = p->right;

} else {

temp = p->left;

while(temp->right != nullptr && temp->right != p) {

temp = temp->right;

}

if(temp->right == nullptr) {

result.push_back(p->val);

temp->right = p;

p = p->left;

} else {

temp->right = nullptr;

p = p->right;

}

}

}

return result;

}

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