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> result;
if(!root)
return result;
stack<TreeNode*> stack;
stack.push(root);
while(!stack.empty())
{
TreeNode* curNode = stack.top();
if(curNode->left)
{
stack.push(curNode->left);
curNode->left = NULL;
}
else
{
result.push_back(curNode->val);
stack.pop();
if(curNode->right)
stack.push(curNode->right);
}
}
return result;
}
};