problem:
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.
thinking:
(1)二叉树的中序遍历,给出递归法和非递归法两种。
(2)递归法的思路是,先递归访问当前结点的左孩子,再打印当前结点的值,再递归访问当前结点的右孩子。
(3)非递归法是借助堆栈实现的,思路也是先将所有左孩子节点放入堆栈中,左孩子为NULL时,打印堆栈顶点结点,
出栈,访问其右孩子。如果其右孩子的左孩子不为NULL,重复上述过程。
code:
非递归法:
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> ret;
stack<TreeNode*> _stack;
TreeNode *tmp=root;
while(tmp!=NULL || !_stack.empty())
{
if(tmp!=NULL)
{
_stack.push(tmp);
tmp=tmp->left;
}
else
{
tmp=_stack.top();
_stack.pop();
ret.push_back(tmp->val);
tmp=tmp->right;
}
}
return ret;
}
};class Solution {
private:
vector<int> ret;
public:
vector<int> inorderTraversal(TreeNode *root) {
inorder(root);
return ret;
}
protected:
void inorder(TreeNode *node)
{
if(node!=NULL)
{
inorder(node->left);
ret.push_back(node->val);
inorder(node->right);
}
}
};leetcode || 94、Binary Tree Inorder Traversal
原文地址:http://blog.csdn.net/hustyangju/article/details/45070335