https://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011?tpId=13&tqId=11171&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
| 日期 | 是否一次通过 | comment |
|----|----|----|
|2019-01-26 13:20|N|实质是preOrder + swap|
|2019-01-27 13:20|Y||
题目:操作给定的二叉树,将其变换为源二叉树的镜像。
image.png1. 递归
public class Solution {
public void Mirror(TreeNode root) {
if(root == null) {
return;
}
TreeNode node = root.left;
root.left = root.right;
root.right = node;
Mirror(root.left);
Mirror(root.right);
}
}
2.非递归
import java.util.*;
public class Solution {
public void Mirror(TreeNode root) {
if(root == null) {
return;
}
Stack<TreeNode> nodeS = new Stack<>();
nodeS.push(root);
while(!nodeS.isEmpty()) {
TreeNode node = nodeS.pop();
TreeNode tempNode = node.left;
node.left = node.right;
node.right = tempNode;
if(node.left != null) {
nodeS.push(node.left);
}
if(node.right != null) {
nodeS.push(node.right);
}
}
}
}
网友评论