二叉树的前序扫描(非递归) (小米云的计算方) )。
java
/* * definitionoftreenode : *公共类treenode { *公共intval; *公共treenode left,right; *publictreenode(intval ) ) { * this.val=val; * this.left=this.right=null; * } */public class solution {/* * @ param root 3360 atree * @ return : preorderinarraylistwhichcontainsnodevalues.*/publiclistintegerpreordertraversal (treenode root )/writeyourcodeherestacktreenodestack=new stack ); ListInteger res=new ArrayList (; if(root==null ) { return res; }stack.push(root ); while (! stack.isEmpty () ({ TreeNode node=stack.pop ); res.add(node.val ); if(node.right!=null}{stack.push(node.right ); (if ) node.left!=null}{stack.push(node.left ); } } return res; }}python
' ' definitionoftreenode : class treenode : def _ _ init _ (self,val ) : self.val=val self.left, self.none ' ' ' class solution : ' ' @ param : root : atree @ return : preorderinarraylistwhichcontainsnodevalues root ) : # writeyourcodehereifrootisnone : return [ ] stack,res=[root], [ ] while stack 3360 node=stack.pop (RES.append ) node.val ) if node.rightisnotnone : stack.append ) node.rightightinal