13_翻转二叉树

简介: 13_翻转二叉树

翻转二叉树

给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

示例 1:

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

示例 2:

输入:root = [2,1,3]
输出:[2,3,1]

示例 3:

输入:root = []
输出:[]

【思路】基本思想就是想要翻转二叉树,只需要把每一个节点的左右孩子交换一下就可以了。关键在于遍历顺序,前中后序应该如何选择呢?

遍历的过程中去翻转每一个节点的左右孩子就可以达到整体翻转的效果。

import java.util.LinkedList;
import java.util.Queue;
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    /*
    // 法一:BFS
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return root;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            while (levelSize-- > 0) {
                TreeNode poll = queue.poll();
                swap(poll);
                if (poll.left != null) {
                    queue.add(poll.left);
                }
                if (poll.right != null) {
                    queue.add(poll.right);
                }
            }
        }
        return root;
    }
    */
    /**
     * 方法二:
      前后序遍历都可以,中序不行,因为先左孩子交换孩子,再根交换孩子(做完后,右孩子已经变成了原来的左孩子),再右孩子交换孩子(此时其实是对原来的左孩子做交换)
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        invertTree(root.left);
        invertTree(root.right);
        swap(root);
        return root;
    }
        //交换左、右孩子节点
        public void swap(TreeNode root) {
            TreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
        }
}
相关文章
|
5月前
力扣226:翻转二叉树
力扣226:翻转二叉树
32 0
|
5月前
|
Java C++ Python
leetcode-226:翻转二叉树
leetcode-226:翻转二叉树
21 0
|
11月前
Leetcode226.翻转二叉树
Leetcode226.翻转二叉树
33 0
|
12月前
leetcode(翻转二叉树)
leetcode(翻转二叉树)
36 0
|
5月前
[LeetCode]—— 226——翻转二叉树
[LeetCode]—— 226——翻转二叉树
LeetCode | 226. 翻转二叉树
LeetCode | 226. 翻转二叉树
|
5月前
|
C++
翻转二叉树(C++)
翻转二叉树(C++)
29 0
|
5月前
|
算法 程序员
【算法训练-二叉树 四】【对称与翻转】对称二叉树、翻转二叉树
【算法训练-二叉树 四】【对称与翻转】对称二叉树、翻转二叉树
44 0
|
12月前
【Leetcode -110.平衡二叉树 -226.翻转二叉树】
【Leetcode -110.平衡二叉树 -226.翻转二叉树】
27 0