Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
非递归中序遍历二叉树。 要注意的是 在写非递归形式的时候可以根据递归形式来思考 比方说递归的二叉树中序遍历算法为:
inoder(Tree T->left);
visit(T->value);
inoder(Tree T->right);
那么我们在转换成迭代时, 也是先处理左子树的情况,先把左子树的根压入栈 再去访问根的值,这之后不要被绕进去了 可以看到递归形势下还是调用inoder函数本身, 那么改变的只是参数,所以在非递归里也是一样,只需要把根变成右子树就好了。
/**
* Definition for binary tree
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<int> result;
vector<TreeNode*> stack;
while (root != NULL || !stack.empty())
{
//deal with leftsubtree
while (root)
{
stack.push_back(root);
root = root->left;
}
//visit value of node
root = stack.back();
result.push_back(root->val);
stack.pop_back();
//deal with right subtree
root = root->right;
}
return result;
}
};