您的位置:首页 > 其它

94、Binary Tree Inorder Traversal

2015-11-27 10:09 381 查看
题目:

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?
解题思路:
迭代法中序遍历。

python版本:

class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def goAlongLeft(x,s):
while(x):
s.append(x)
x = x.left
stack,res = [],[]
x = root
while(True):
goAlongLeft(x,stack)
if(len(stack)==0):break
x = stack.pop()
res.append(x.val)
x = x.right
return res


c++版本:

class Solution {
public:
void goAlongLeft(TreeNode *x,stack<TreeNode *>&s){
while(x){
s.push(x);
x = x->left;
}
}
vector<int> inorderTraversal(TreeNode* root) {
TreeNode *x = root;
vector<int> res;
stack<TreeNode *>s;
while(true){
goAlongLeft(x,s);
if(s.empty())break;
x = s.top();s.pop();
res.push_back(x->val);
x = x->right;
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: