您的位置:首页 > 其它

二叉树的中序遍历

2015-09-28 12:55 489 查看


容易 二叉树的中序遍历

39%
通过

给出一棵二叉树,返回其中序遍历
您在真实的面试中是否遇到过这个题?

Yes

样例

给出二叉树
{1,#,2,3}
,
1
\
2
/
3

返回
[1,3,2]
.

挑战

你能使用非递归算法来实现么?

标签 Expand

递归 二叉树 二叉树遍历

/**
* Definition of TreeNode:
* class TreeNode {
* public:
*     int val;
*     TreeNode *left, *right;
*     TreeNode(int val) {
*         this->val = val;
*         this->left = this->right = NULL;
*     }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Inorder in vector which contains node values.
*/
vector<int> ret;
stack<TreeNode *> tmp;
public:
vector<int> inorderTraversal(TreeNode *root) {
// write your code here
//tmp.clear();
TreeNode *s = root;
while(!tmp.empty() || s){
while(s){
tmp.push(s);
s = s->left;
}
ret.push_back(tmp.top()->val);
s = tmp.top()->right;
tmp.pop();
}
return ret;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: