LintCode -- binary-tree-inorder-traversal(二叉树的中序遍历)
原题链接:http://www.lintcode.com/zh-cn/problem/binary-tree-inorder-traversal/
给出一棵二叉树,返回其中序遍历
样例
给出二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [1,3,2]
.
挑战
你能使用非递归算法来实现么?
非递归实现(C++、Java、Python):
/**
* 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.
*/
public:
vector<int> inorderTraversal(TreeNode *root) {
// write your code here
vector<TreeNode *> p;
vector<int> res;
while(root != NULL || p.size() != 0){
while(root != NULL){
p.push_back(root);
root = root->left;
}
root = p.back();
p.pop_back();
res.push_back(root->val);
root = root->right;
}
return res;
}
};
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Inorder in ArrayList which contains node values.
*/
public ArrayList<Integer> inorderTraversal(TreeNode root) {
// write your code here
ArrayList<TreeNode> p = new ArrayList<TreeNode>();
ArrayList<Integer> res = new ArrayList<Integer>();
while(root != null || p.size() != 0){
while(root != null){
p.add(root);
root = root.left;
}
root = p.get(p.size()-1);
p.remove(p.size()-1);
res.add(root.val);
root = root.right;
}
return res;
}
}
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: Inorder in ArrayList which contains node values.
"""
def inorderTraversal(self, root):
# write your code here
p = [root]
res = [0]
while root is not None or len(p) != 1:
while root is not None:
p.append(root)
root = root.left
root = p[len(p)-1]
del p[len(p)-1]
res.append(root.val)
root = root.right
n = len(res)
return res[1:n]