思路:
二叉树的中序遍历。
方法一:DFS。
/**
* 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 {
private:
void dfs(vector<int>& ans, TreeNode* node) {
if(node == nullptr) return;
if(node->left) {
dfs(ans, node->left);
}
ans.push_back(node->val);
if(node->right) {
dfs(ans, node->right);
}
}
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
dfs(ans, root);
return ans;
}
};
方法二:迭代。
时间复杂度O(N),空间复杂度O(N)
/**
* 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;
TreeNode* p = root;
stack<TreeNode*> s;
while(!s.empty() || p != nullptr) {
if(p != nullptr) {
s.push(p);
p = p->left;
}else {
p = s.top();
s.pop();
ans.push_back(p->val);
p = p->right;
}
}
return ans;
}
};
方法三: