给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
inorder(root, ans);
return ans;
}
void inorder(TreeNode* root, vector<int> &ans)
{
if(root == NULL)
return;
inorder(root->left, ans);
ans.push_back(root->val);
inorder(root->right, ans);
}
};
左根右
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
stack<TreeNode*> stk;
while(root || !stk.empty())
{
while(root)
{
stk.push(root);
root = root->left;
}
root = stk.top();
ans.push_back(root->val);
stk.pop();
root = root->right;
}
return ans;
}
};