JZ18-二叉树的镜像
二叉树的镜像
https://www.nowcoder.com/practice/a9d0ecbacef9410ca97463e4a5c83be7?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
class Solution { //递归 public void Mirror(TreeNode pRoot) { if (pRoot == null) { return; } Mirror(pRoot.left); Mirror(pRoot.right); TreeNode temp = pRoot.left; pRoot.left = pRoot.right; pRoot.right = temp; } // public void Mirror2(TreeNode pRoot) { if (pRoot == null) { return; } Stack<TreeNode> stack = new Stack<>(); stack.push(pRoot); while (!stack.isEmpty()) { TreeNode tempRoot = stack.pop(); if (tempRoot == null) { continue; //无需交换 } if (tempRoot.left == null && tempRoot.right == null) { continue; //无需交换 } TreeNode temp = tempRoot.left; tempRoot.left = tempRoot.right; tempRoot.right = temp; stack.push(tempRoot.right); //在此题可以随便换位置,但是在Dfs中,只能先右后左 stack.push(tempRoot.left); } } }