Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
Subscribe to see which companies asked this question
递归写法
/**
* 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> v1;
// if(root==NULL) return v1;
inorder(root,v1);
return v1;
}
void inorder(TreeNode* root ,vector<int>& v1)
{
if(root==NULL)
return ;
if(root->left)
inorder(root->left,v1);
v1.push_back(root->val);
if(root->right)
inorder(root->right,v1);
return ;
}
};
非递归写法:
/**
* 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> v1;
if(root==NULL) return v1;
stack<TreeNode*> s1;
while(root ||(!s1.empty()))
{
while(root)
{
s1.push(root);
root=root->left;
}
if(s1.size())
{
root=s1.top();
v1.push_back(root->val);
root=root->right;
s1.pop();
}
}
return v1;
}
};