二叉树先序,中序,后序(递归,非递归)
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362?tpId=196&&tqId=37153&rp=1&ru=/activity/oj&qru=/ta/job-code-total/question-ranking
第一种递归:
public int[][] threeOrders (TreeNode root) { // write code here List<Integer> preList=new ArrayList<>(); List<Integer> midList=new ArrayList<>(); List<Integer> hList=new ArrayList<>(); preDfs(root,preList); midDfs(root,midList); hDfs(root,hList); int len = preList.size(); int[][] res=new int[3][len]; for(int i=0;i<len;i++){ res[0][i]=preList.get(i); res[1][i]=midList.get(i); res[2][i]=hList.get(i); } return res; } public void preDfs(TreeNode root,List<Integer> preList){ if(root==null) return; preList.add(root.val); preDfs(root.left,preList); preDfs(root.right,preList); } public void midDfs(TreeNode root,List<Integer> midList){ if(root==null) return; midDfs(root.left,midList); midList.add(root.val); midDfs(root.right,midList); } public void hDfs(TreeNode root,List<Integer> hList){ if(root==null) return; hDfs(root.left,hList); hDfs(root.right,hList); hList.add(root.val); }
第二种非递归:
public int[][] threeOrders (TreeNode root) { // write code here List<Integer> preList=new ArrayList<>(); List<Integer> midList=new ArrayList<>(); List<Integer> hList=new ArrayList<>(); System.out.println(0); pre(root,preList); mid(root,midList); h(root,hList); System.out.println(preList.size()); int len = preList.size(); int[][] res=new int[3][len]; for(int i=0;i<len;i++){ res[0][i]=preList.get(i); res[1][i]=midList.get(i); res[2][i]=hList.get(i); } return res; } public void pre(TreeNode root,List<Integer> list){ if(root==null) return; Stack<TreeNode> stack=new Stack<>(); while(root!=null){ stack.push(root); list.add(root.val); root=root.left; } while(stack.size()>0){ TreeNode t=stack.pop(); if(t.right!=null){ TreeNode r=t.right; while(r!=null){ stack.push(r); list.add(r.val); r=r.left; } } } } public void mid(TreeNode root,List<Integer> list){ if(root==null) return; Stack<TreeNode> stack=new Stack<>(); while(root!=null){ stack.push(root); root=root.left; } while(stack.size()>0){ TreeNode t=stack.pop(); list.add(t.val); if(t.right!=null){ TreeNode r=t.right; while(r!=null){ stack.push(r); r=r.left; } } } } //按照先右再左的方式压入栈内,与先序相反。压入的时候添加进list,最后反转即可。 public void h(TreeNode root,List<Integer> list){ if(root==null) return; Stack<TreeNode> stack=new Stack<>(); while(root!=null){ stack.push(root); list.add(root.val); root=root.right; } while(stack.size()>0){ TreeNode t=stack.pop(); if(t.left!=null){ TreeNode r=t.left; while(r!=null){ stack.push(r); list.add(r.val); r=r.right; } } } Collections.reverse(list); }