您的位置:首页 > 其它

27、二叉树的镜像

2018-04-03 16:27 190 查看

1、递归的方法

将根节点的左右子树对调,再将左右子树的左右子树对调,依次递归

/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}

}
*/
public class Solution {
public void Mirror(TreeNode root) {
if(root == null) return;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
Mirror(root.left);
Mirror(root.right);
}
}


2、循环的方法

import java.util.ArrayDeque;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}

}
*/
public class Solution {
public void Mirror(TreeNode root) {
if(root==null ) return;
ArrayDeque<TreeNode> stack = new ArrayDeque<TreeNode>();
//将根节点压入栈
stack.push(root);
while(!stack.isEmpty())
{
//弹出top节点并交换该结点的左右子树
TreeNode father = stack.pop();
TreeNode temp = father.left;
father.left = father.right;
father.right = temp;
//左子树不为空则压入栈
if(father.left!=null)
stack.push(father.left);
//右子树不为空则压入栈
if(father.right!=null)
stack.push(father.right);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: