1、题目描述
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
2、问题描述:
非递归实现,中序。
3、问题关键:
4、C++代码:
递归
class Solution {
public:
vector res;
vector inorderTraversal(TreeNode* root) {
if (!root) return vector();
dfs(root);
return res;
}
void dfs(TreeNode* root) {
if (!root) return;
dfs(root->left);
res.push_back(root->val);
dfs(root->right);
}
};
模拟法。(stack)
/**
* 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 inorderTraversal(TreeNode* root) {
stack st;
vector res;
auto now = root;
while (now || !st.empty()) {
while (now) {
st.push(now);
now = now->left;
}
if (!st.empty()) {
now = st.top();
st.pop();
res.push_back(now->val);
now = now->right;
}
}
return res;
}
};