publicvoidpreOrder1(TreeNode root){//递归if(root ==null){return;}System.out.print(root.val +" ");preOrder1(root.left);preOrder1(root.right);}publicvoidpreOrder2(TreeNode root){if(root ==null){return;}TreeNode current;LinkedList<TreeNode> s =newLinkedList<>();
s.addFirst(root);while(!s.isEmpty()){
current = s.removeFirst();System.out.print(current.val +" ");if(current.right !=null){
s.addFirst(current.right);}if(current.left !=null){
s.addFirst(current.left);}}}
3、中序遍历(递归&非递归)
publicvoidinOrder1(TreeNode root){//递归if(root ==null){return;}inOrder1(root.left);System.out.print(root.val +" ");inOrder1(root.right);}publicvoidinOrder2(TreeNode root){TreeNode current = root;LinkedList<TreeNode> s =newLinkedList<TreeNode>();while(!s.isEmpty()|| current !=null){while(current !=null){
s.addFirst(current);
current = current.left;}if(!s.isEmpty()){
current = s.removeFirst();System.out.print(current.val +" ");
current = current.right;}}}
4、后序遍历(递归&非递归)
publicvoidpostOrder1(TreeNode root){//递归if(root ==null){return;}postOrder1(root.left);postOrder1(root.right);System.out.print(root.val +" ");}publicvoidpostOrder2(TreeNode root){TreeNode current = root;LinkedList<TreeNode> s1 =newLinkedList<>();LinkedList<TreeNode> s2 =newLinkedList<>();while(!s1.isEmpty()|| current !=null){while(current !=null){
s1.addFirst(current);
s2.addFirst(current);
current = current.right;}if(!s1.isEmpty()){
current = s1.removeFirst();
current = current.left;}}while(!s2.isEmpty()){System.out.print(s2.removeFirst().val +" ");}}