面试题19:二叉树的镜像
2017-08-17 20:08
573 查看
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。输入描述:
二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \11 9 7 5
代码:
/**
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;
}
if(root.left==null&&root.right==null){
return;
}
TreeNode temp = null;
temp = root.left;
root.left=root.right;
root.right=temp;
if(root.left!=null){
Mirror(root.left);
}
if(root.right!=null){
Mirror(root.right);
}
}
}
非递归:
import java.util.*;
public class Solution {
public void Mirror(TreeNode root) {
if(root == null) return;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.empty()) {
TreeNode node = stack.pop();
if(node.left != null || node.right != null) {
TreeNode nodeLeft = node.left;
TreeNode nodeRight = node.right;
node.left = nodeRight;
node.right = nodeLeft;
}
if(node.left != null) stack.push(node.left);
if(node.right != null) stack.push(node.right);
}
}
}
相关文章推荐
- 剑指Offer之面试题19:二叉树的镜像
- 面试题19二叉树的镜像
- 面试题19:二叉树的镜像
- 面试题 19 : 二叉树的镜像
- 剑指offer阅读笔记 之面试题19 实现二叉树的镜像 之 又复习一遍二叉树
- 剑指offer-面试题19:二叉树的镜像
- [剑指offer][面试题19]二叉树的镜像
- 剑指offer_面试题19_二叉树的镜像
- 剑指offer代码解析——面试题19二叉树的镜像
- 剑指offer-面试题19-二叉树的镜像
- 【面试题】剑指Offer-19-二叉树的镜像
- 剑指offer之面试题19:二叉树的镜像
- 面试题19:二叉树的镜像
- 剑指offer 面试题19 二叉树的镜像
- 剑指Offer---面试题19:镜像二叉树
- 剑指Offer面试题19(Java版):二叉树的镜像
- 面试题19:二叉树的镜像
- 剑指offer代码解析——面试题19二叉树的镜像
- 【剑指Offer学习】【面试题19 :二叉树的镜像】
- 【剑指offer】4.2画图让抽象问题形象化——面试题19:二叉树的镜像