标签:
给定一个二叉树,返回其中序遍历的节点的值。
例如:
给定二叉树为 {1, #, 2, 3}
1
2
/
3
返回 [1, 3, 2]
备注:用递归是微不足道的,你可以用迭代来完成它吗?
Given a binary tree, return the inorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3},
1
2
/
3
return [1,3,2].
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> inorderTraversal(TreeNode* root) {
if (root != NULL) {
inorderTraversal(root->left);
v.push_back(root->val);
inorderTraversal(root->right);
}
return v;
}
};
接下是是时候写成迭代咯~
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> tempStack;
while (!tempStack.empty() || root != NULL) {
if (root != NULL) {
tempStack.push(root);
root = root->left;
}
else {
root = tempStack.top();
result.push_back((tempStack.top())->val);
tempStack.pop();
root = root->right;
}
}
return result;
}
};
LeetCode 94 Binary Tree Inorder Traversal(二叉树的中序遍历)+(二叉树、迭代)
标签:
原文地址:http://blog.csdn.net/nomasp/article/details/50930671