94. 二叉树的中序遍历
二叉树的中序遍历。
中序遍历我记为 左 - 中- 右。
Inorder (Left, Root, Right) : 4 2 5 1 3
树的遍历大部分都是可以给出迭代和递归两种做法的,两种做法的时间和空间复杂度一样,时间都是O(n),空间都是O(h)。
递归实现:
class Solution { public List<Integer> inorderTraversal(TreeNode head) { List<Integer> list=new ArrayList<>(); if(head==null){ return list; } process(head,list); return list; } public void process(TreeNode node,List<Integer> list){ if(node==null){ return; } process(node.left,list); list.add(node.val); process(node.right,list); } }
非递归实现:
中:左中右
第一阶段:先遍历左子树入stack
第二阶段:弹出并打印cur,cur.right重复阶段一
class Solution { public List<Integer> inorderTraversal(TreeNode head) { if(head==null){ return new ArrayList<>(); } List<Integer> result=new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); TreeNode cur=head; while (!stack.isEmpty()||cur!=null){ if(cur!=null){ stack.push(cur); cur=cur.left; }else { cur=stack.pop();//注意这里,弹出当前节点后,处理时机变成当前节点
result.add(cur.val); cur=cur.right; } } return result; } }
Morris序改中序遍历
class Solution { public List<Integer> inorderTraversal(TreeNode head) { List<Integer> list=new ArrayList<>(); if(head==null){ return list; } TreeNode cur=head; TreeNode mostRight; while(cur!=null){ mostRight=cur.left; if(mostRight!=null){ //有左节点 while (mostRight.right!=null&&mostRight.right!=cur){ mostRight=mostRight.right; } if(mostRight.right==null){ //第一次来到cur mostRight.right=cur; cur=cur.left; continue; }else{ //第二次来到cur mostRight.right=null; } } list.add(cur.val);//第二次来到cur或只有一次来到的节点位置 cur=cur.right; } return list; } }