144 Binary Tree Preorder Traversal(二叉树的前序遍历)+(二叉树迭代)
Posted nomasp
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了144 Binary Tree Preorder Traversal(二叉树的前序遍历)+(二叉树迭代)相关的知识,希望对你有一定的参考价值。
翻译
给定一个二叉树,返回其前序遍历的节点的值。
例如:
给定二叉树为 {1,#, 2, 3}
1
2
/
3
返回 [1, 2, 3]
备注:用递归是微不足道的,你可以用迭代来完成它吗?
原文
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?
分析
题目让咱试试迭代呢,不过还是先老老实实把递归给写出来再说吧~
/**
* 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> v;
vector<int> preorderTraversal(TreeNode* root) {
if (root != NULL) {
v.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
return v;
}
};
紧接着,咱来写迭代的……
/**
* 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> result;
stack<TreeNode*> tempStack;
while (!tempStack.empty() || root != NULL) {
if (root != NULL) {
result.push_back(root->val);
tempStack.push(root);
root = root->left;
}
else {
root = tempStack.top();
tempStack.pop();
root = root->right;
}
}
return result;
}
};
以上是关于144 Binary Tree Preorder Traversal(二叉树的前序遍历)+(二叉树迭代)的主要内容,如果未能解决你的问题,请参考以下文章
144. Binary Tree Preorder Traversal
144. Binary Tree Preorder Traversal
144. Binary Tree Preorder Traversal
144. Binary Tree Preorder Traversal