from typing import ( List,)from lintcode import ( TreeNode,)"""Definition of TreeNode:class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None"""classSolution:""" @param root: A Tree @return: Inorder in ArrayList which contains node values. """definorder_traversal(self,root: TreeNode) -> List[int]:# write your code here res = [] stack = [] cur = root#一个while判断cur和stack即可while cur or stack:while cur: stack.append(cur) cur = cur.left cur = stack.pop()#List函数没有add res.append(cur.val)#只移动指针,不需要塞入栈,因为中序的话root已经遍历了,右树可以直接遍历无需栈。 cur = cur.right#记得返回结果return res
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<Integer>();
if(root == null)
return ret;
Stack<TreeNode> s = new Stack<TreeNode>();
TreeNode cur = root;
while(cur != null || !s.isEmpty()){
while(cur != null){
s.push(cur);
cur = cur.left;
}
cur = s.pop();
ret.add(cur.val);
cur = cur.right;
}
return ret;
}
Recursive
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<Integer>();
if(root == null)
return ret;
List<Integer> left = inorderTraversal(root.left);
List<Integer> right = inorderTraversal(root.right);
ret.addAll(left);
ret.add(root.val);
ret.addAll(right);
return ret;
}