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?
confused what "{1,#,2,3}" means? >
read more on how binary tree is serialized on OJ.
用非递归的方法实现二叉树的中序遍历。
/**
* 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) {
vector<int>result;
stack<TreeNode*>st;
TreeNode*node=root;
//左孩子不断入栈
while(node){st.push(node); node=node->left;}
while(!st.empty()){
//访问栈顶元素
node=st.top(); st.pop();
result.push_back(node->val);
node=node->right;
//右子树的左孩子不断入栈
while(node){st.push(node); node=node->left;}
}
return result;
}
};LeetCode: Binary Tree Inorder Traversal [094],布布扣,bubuko.com
LeetCode: Binary Tree Inorder Traversal [094]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/27958187