题目如下:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1 \ 2 / 3return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
题目分析:
二叉树的常规题目包括进行树的前序,中序,后序,层序遍历。使用对于其中的前3个,可以使用递归和非递归两种方式。本题是进行中序遍历,鼓励使用非递归。之前也写过类似的文章。所以直接贴出提交到leetcode的代码如下。
//8ms过大集合
/**
* 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> inorderTraversal(TreeNode *root) {
vector<int> res_vec;
if(root==NULL)
return res_vec;
TreeNode* cur_node=root;
std::stack<TreeNode*> stack_left;
while(cur_node!=NULL){
stack_left.push(cur_node);
cur_node=cur_node->left;
}
while(!stack_left.empty()){
cur_node=stack_left.top();
res_vec.push_back(cur_node->val);
cur_node=cur_node->right;
stack_left.pop();
while (cur_node!=NULL) {
stack_left.push(cur_node);
cur_node=cur_node->left;
}
}
return res_vec;
}
};