题目:
给出一棵二叉树,返回其中序遍历
给出二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [1,3,2]
.
代码:/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Inorder in vector which contains node values.
*/
public:
vector<int> inorderTraversal(TreeNode *root) {
// write your code here
vector<int>ss;
TreeNode *s[1000];
int top=-1;
while(root!=NULL||top!=-1)
{
while(root!=NULL)
{
//cout<<root->val;
//ss.push_back(root->val);
s[++top]=root;
root=root->left;
//ss.push_back(root->val);
}
ss.push_back(s[top]->val);
if(top!=-1)
{ root=s[top--];
root=root->right;
}
}
return ss;
}
};
感想:和前序遍历一样,直接照搬了。