# Definition for a binary tree node.classTreeNode(object):def__init__(self,x):self.val=xself.left=Noneself.right=NoneclassSolution(object):definorderTraversal(self,root):""" :type root: TreeNode :rtype: List[int] """ret=[]ifnotroot:returnretstack=[]node=rootwhilenode:stack.append(node)node=node.leftwhilestack:node=stack.pop()ret.append(node.val)# push the left subtree of right childnode=node.rightwhilenode:stack.append(node)node=node.leftreturnretif__name__=="__main__":sol=Solution()node1=TreeNode(1)node2=TreeNode(2)node3=TreeNode(3)node1.right=node2node2.left=node3printsol.inorderTraversal(node1)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassSolution{publicList<Integer>inorderTraversal(TreeNoderoot){List<Integer>ret=newLinkedList<Integer>();Stack<TreeNode>stack=newStack<TreeNode>();TreeNodecur=root;while(cur!=null||!stack.empty()){// 把左子树插入while(cur!=null){stack.add(cur);cur=cur.left;}cur=stack.pop();ret.add(cur.val);cur=cur.right;}returnret;}}