算法练习(16)-水平翻转一颗二叉树

依旧还是层次遍历, 按层入队, 然后出队时, 交换左右节点

public static void flipTree(TreeNode node) {
    if (node == null) {
        return;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(node);
    while (!queue.isEmpty()) {
        TreeNode n = queue.poll();
        if (n.left != null) {
            queue.add(n.left);
        }
        if (n.right != null) {
            queue.add(n.right);
        }
        TreeNode left = n.left;
        TreeNode right = n.right;
        n.left = right;
        n.right = left;
    }
}
posted @ 2021-11-03 12:07  菩提树下的杨过  阅读(99)  评论(0编辑  收藏  举报