题目描述:
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?
思路:
递归:左节点,当前节点值,右节点。
迭代:从根结点开始不断把左结点加入到栈中,然后把栈顶结点值加入到ans中,然后指针指向到右节点,重复上述过程。
递归代码:
/**
* 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> ans;
if (root == NULL) return ans;
dfs(ans, root);
return ans;
}
void dfs(vector<int>& ans, TreeNode* root) {
if (root->left != NULL) dfs(ans, root->left);
ans.push_back(root->val);
if (root->right != NULL) dfs(ans, root->right);
}
};
迭代代码:
/**
* 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> ans;
stack<TreeNode*> st;
TreeNode* cur = root;
while(cur || !st.empty()) {
if (cur) {
while(cur) {
st.push(cur);
cur=cur->left;
}
}else {
TreeNode* tmp = st.top();
st.pop();
ans.push_back(tmp->val);
cur = tmp->right;
}
}
return ans;
}
};