镜像二叉树

二叉树的镜像

http://www.nowcoder.com/questionTerminal/564f4c26aa584921bc75623e48ca3011

手动压栈

import java.util.Stack;
public class Solution {
  public void Mirror(TreeNode root) {

    // 空树
    if (root == null) {
      return;
    }
    // 左右均为空
    if (root.left == null && root.right == null) {
      return;
    }

    // 用来遍历的栈
    Stack<TreeNode> stack = new Stack<TreeNode>();

    stack.push(root);

    TreeNode curNode;
    TreeNode tempNode;

    // 深度优先
    while (!stack.isEmpty()) {
      curNode = stack.pop();
      if(curNode == null) {
        continue;
      }
      if(curNode.left == null && curNode.right==null) {
        continue;
      }
      // 交换
      tempNode = curNode.left;
      curNode.left = curNode.right;
      curNode.right = tempNode;
      stack.push(curNode.left);
      stack.push(curNode.right);
    }
  }
}
全部评论
请问下这个是深度优先还是广度优先啊?看起来是一层一层去遍历
点赞 回复 分享
发布于 2020-07-15 21:55
把root压入栈是怎么压入的,得到一个栈,栈里面又是怎么存储的呢 ?
点赞 回复 分享
发布于 2020-02-15 14:03
不太看得懂呀,博主,可以再说详细一点嘛,谢谢 小白一个
点赞 回复 分享
发布于 2020-02-15 14:01

相关推荐

评论
13
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务