InvertBinaryTree

  • 2022-12-14
  • 浏览 (513)

InvertBinaryTree.java 源码

package datastructure.tree.leetcode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author roseduan
 * @time 2021/9/20 6:07 下午
 * @description 翻转二叉树
 */
public class InvertBinaryTree {

    /**
     * 递归
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode left = root.left;
        root.left = root.right;
        root.right = left;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    /**
     * 广度优先
     */
    public TreeNode invertTree2(TreeNode root) {
        if (root == null) {
            return null;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            TreeNode left = node.left;
            node.left = node.right;
            node.right = left;

            if (node.left != null) {
                queue.add(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
            }
        }
        return root;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}

你可能感兴趣的文章

BinaryTreeInorderTraversal

BinaryTreeLevelOrderTraversal

BinaryTreePostorderTraversal

0  赞