您的位置:首页 > 其它

LeetCode OJ 之 Binary Tree Inorder Traversal (二叉树的中序遍历)

2014-12-17 09:32 537 查看

题目:

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?

思路:

二叉树的非递归遍历可以参考:http://blog.csdn.net/u012243115/article/details/40615603

递归版代码:

/**
* 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;
inorderTraversal(root,result);
return result;
}
void inorderTraversal(TreeNode *root , vector<int> &result)
{
if(root == NULL)
return ;
inorderTraversal(root->left,result);
result.push_back(root->val);
inorderTraversal(root->right,result);
}
};

非递归版代码:

/**
* 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 *> stk;
TreeNode *p = root;
//循环结束条件是p为空且栈为空
while( p != NULL || !stk.empty())
{
//如果当前结点非空,则入栈,下次遍历左孩子
if(p != NULL)
{
stk.push(p);
p = p->left;
}
//如果当前结点为空,出栈,遍历右孩子
else
{
p = stk.top();
stk.pop();
result.push_back(p->val);
p = p->right;
}
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐