[leetCode]226. 翻转二叉树

题目

链接:https://leetcode-cn.com/problems/invert-binary-tree

翻转一棵二叉树。

示例:

输入:

     4
   /   
  2     7
 /    / 
1   3 6   9
输出:

     4
   /   
  7     2
 /    / 
9   6 3   1

BFS

思路: 按照二叉树进行分层遍历,每遍历一层的节点就交换该节点的左右子树

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return root;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            TreeNode temp = cur.left;
            cur.left = cur.right;
            cur.right = temp;
            if (cur.left!=null) 
                queue.offer(cur.left);
            if (cur.right != null) 
                queue.offer(cur.right);
        }
        return root;
    }
}

中序遍历

思路: 以中序遍历遍历整个二叉树,遍历到中间节点时交换该节点的左右子树。

class Solution {
    public TreeNode invertTree(TreeNode root) {
        return dfs(root);
    }

    private TreeNode dfs(TreeNode node) {
        if (node == null) {
            return null;
        }
        // 中
        TreeNode temp = node.left;
        node.left = node.right;
        node.right = temp;
        // 左
        dfs(node.left);
        // 右
        dfs(node.right);

        return node;
    }
}
原文地址:https://www.cnblogs.com/PythonFCG/p/13908608.html