二叉树的镜像_JAVA_简单

二叉树的镜像

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

递归算法

  • 先交换该节点的左右孩子,再将孩子作为根节点作为参数调用函数,节点为空为终止条件

    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);
      }
    }

非递归算法

  • 进行层次遍历的处理,每次交换该节点的左右孩子,再将孩子作为根节点进入队列,队列为空为终止条件
import java.util.*;
public class Solution {
    public void Mirror(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList();

        // 队列不为空
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode node = queue.poll();
            // 当前节点不为空才处理
            if(node == null) {
                continue;
            }

            // 交换节点
            TreeNode tmpNode = node.left;
            node.left = node.right;
            node.right = tmpNode;

            // 孩子进队列
            queue.offer(node.left);
            queue.offer(node.right);
        }
    }
}
全部评论

相关推荐

1jian10:48h没写面评会变成这样
点赞 评论 收藏
分享
03-31 21:47
东南大学 C++
彭于晏前来求offe...:吓晕了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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