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?
题意:给一棵二叉树,输出中序遍历
思路;首先想到的就是递归,但是看到那句note之后想了一下用非递归的解决了,就是用一个栈模拟系统的栈,中序遍历的非递归还是很好写的,等明后连天研究一下后序和前序的。
坑:暂无
代码:
/**
* 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> inorderTraversal(TreeNode* root) {
vector<int> ans;
GetAns(ans, root);
return ans;
}
void GetAns(vector<int> &ans, TreeNode* root)
{
stack<TreeNode*> tree;
TreeNode *p = root;
while(p!=NULL||!tree.empty())
{
if(p!=NULL)
{
tree.push(p);
p = p->left;
}
else
{
p = tree.top();
tree.pop();
ans.push_back(p->val);
p = p->right;
}
}
}
};