1. 题目
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?
2. 思路
递归相对简单, 递归左子树,压入根节点,递归右子树,结束。
模拟遍历的过程。迭代的方式采用栈来记录遍历的路径。初始将root压入。
然后每次从栈顶开始,持续将栈顶的左子树非空的左子树压栈。如果为空,则表示达到了当前的最左侧,输出当前节点。让后持续向上并输出,找到第一个右子树非空的情况进行压栈。
栈空的时候表示全部遍历完成。
3. 代码-递归
/**
* 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> ret;
if (root == NULL) { return ret; }
//if (root->left == NULL && root->right == NULL) { ret.push_back(root->val); return ret; }
vector<int> left = inorderTraversal(root->left);
vector<int> right = inorderTraversal(root->right);
left.push_back(root->val);
for (auto it = right.begin(); it != right.end(); it++) {
left.push_back(*it);
}
return left;
}
};
4. 代码-迭代
/**
* 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:
TreeNode* _stack[1024];
int _top;
public:
vector<int> inorderTraversal(TreeNode* root) {
_top = 0;
vector<int> ret;
if (root == NULL) { return ret; }
_stack[_top] = root;
while (_top >= 0) {
if (_stack[_top]->left != NULL) {
_stack[_top+1] = _stack[_top]->left;
_top++;
} else {
ret.push_back(_stack[_top]->val);
if (_stack[_top]->right != NULL) {
_stack[_top] = _stack[_top]->right;
} else {
_top--;
while (_stack[_top]->right == NULL && _top >= 0) {
ret.push_back(_stack[_top]->val);
_top--;
}
if (_top >= 0) {
ret.push_back(_stack[_top]->val);
_stack[_top] = _stack[_top]->right;
}
}
}
}
return ret;
}
};