翻转一棵二叉树。
示例:
针对二叉树的问题,解题之前一定要想清楚究竟是前中后序遍历,还是层序遍历
这道题目使用前序遍历和后序遍历都可以,唯独中序遍历不方便,因为中序遍历会把某些节点的左右孩子翻转了两次!建议拿纸画一画,就理解了
那么层序遍历可以不可以呢?依然可以的!只要把每一个节点的左右孩子翻转一下的遍历方式都是可以的!
1、前序、后序遍历递归实现
public TreeNode invertTree(TreeNode root) { postInvert(root); return root; } private void postInvert(TreeNode root){ if(root==null){ return; } //swap(root); postInvert(root.left); postInvert(root.right); swap(root); } private void swap(TreeNode root){ TreeNode temp=root.left; root.left=root.right; root.right=temp; }
2、层序遍历
public TreeNode invertTree(TreeNode root) { levelOrder(root); return root; } private void levelOrder(TreeNode root){ if(root==null){ return; } TreeNode cur=root; LinkedList<TreeNode> queue=new LinkedList<>(); queue.add(cur); while(!queue.isEmpty()){// cur l r .l r.l r cur=queue.pop(); //System.out.println(cur.val); swap(cur); if(cur.left!=null){ queue.add(cur.left); } if(cur.right!=null){ queue.add(cur.right); } } } private void swap(TreeNode root){ TreeNode temp=root.left; root.left=root.right; root.right=temp; }
3、前序遍历非递归实现
public TreeNode invertTree(TreeNode root) { preOrder(root); return root; } private void preOrder(TreeNode root){ if(root==null){ return; } //cur l r. stack cur r l TreeNode cur=root; Stack<TreeNode> stack=new Stack<>(); stack.push(cur); while(!stack.isEmpty()){ cur=stack.pop(); swap(cur); if(cur.right!=null){ stack.push(cur.right); } if(cur.left!=null){ stack.push(cur.left); } } } private void swap(TreeNode root){ TreeNode temp=root.left; root.left=root.right; root.right=temp; }
4、后序遍历非递归实现
public TreeNode invertTree(TreeNode root) { postOrder(root); return root; } private void postOrder(TreeNode root){ if(root==null){ return; } //l r cur. stack1 cur l r. stack cur r l TreeNode cur=root; Stack<TreeNode> stack1=new Stack<>(); Stack<TreeNode> stack2=new Stack<>(); stack1.push(cur); while(!stack1.isEmpty()){ cur=stack1.pop(); stack2.push(cur); if(cur.left!=null){ stack1.push(cur.left); } if(cur.right!=null){ stack1.push(cur.right); } } while(!stack2.isEmpty()){ swap(stack2.pop()); } } private void swap(TreeNode root){ TreeNode temp=root.left; root.left=root.right; root.right=temp; }