题解 | #二叉树的镜像#
二叉树的镜像
https://www.nowcoder.com/practice/a9d0ecbacef9410ca97463e4a5c83be7
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
// 此题目就是交换二叉树的两个孩子节点的位置,应该不难
// 试一下后续遍历,然后在每个节点交换左右孩子的指针
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return TreeNode类
*/
public TreeNode Mirror (TreeNode pRoot) {
// write code here
if(pRoot==null) return null;
if(pRoot.left!=null) Mirror(pRoot.left);
if(pRoot.right!=null) Mirror(pRoot.right);
TreeNode temp;
temp = pRoot.left;
pRoot.left = pRoot.right;
pRoot.right = temp;
return pRoot;
}
}
有关二叉树的题目好多还是用了递归的思想,不过这里应该要局限于只能用先序和后续遍历,因为中序会导致重复操作
查看30道真题和解析