二叉树的镜像问题
题目描述如下图所示:
解题思路:利用栈的先进后出特性去做;也可以利用队列去做,只要保证right先进队列就行
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 {
public void Mirror(TreeNode root) {
if(root==null)return;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode tn = stack.pop();
if(tn.left != null||tn.right != null){
TreeNode temp = tn.left;
tn.left = tn.right;
tn.right = temp;
}
if(tn.left != null) {
stack.push(tn.left);
}
if(tn.right != null) {
stack.push(tn.right);
}
}
}
}
- 上一篇: 扑克牌问题
- 下一篇: 二分法使用无符号位右移运算求解上中位数