C/C++教程

LeetCode.226. 翻转二叉树

本文主要是介绍LeetCode.226. 翻转二叉树,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

LeetCode.226. 翻转二叉树

难度:easy

 

BFS和DFS两种方法: 

/**
 * 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;
 *     }
 * }
 */
// DFS
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return root;
        }
        TreeNode tmpNode = root.left;
        root.left = root.right;
        root.right = tmpNode;
        
        invertTree(root.left);
        invertTree(root.right);

        return root;
    }
}

//BFS
class Solution {
    public TreeNode invertTree(TreeNode root) {
        List<Double> ansList = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return null;
        }
        
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
           
            for (int i = 0; i < size; i++) {
                TreeNode tmpNode = queue.poll();
                // 反转左右儿子
                TreeNode node = tmpNode.left;
                tmpNode.left = tmpNode.right;
                tmpNode.right = node;
                
                if (tmpNode.left != null) {
                    queue.offer(tmpNode.left);
                }
                if (tmpNode.right != null) {
                    queue.offer(tmpNode.right);
                }
            }
        }
        return root;
    }
}

 

这篇关于LeetCode.226. 翻转二叉树的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!