LeetCode.226. 翻转二叉树

LeetCode.226. 翻转二叉树

难度:easy

LeetCode.226. 翻转二叉树

 LeetCode.226. 翻转二叉树

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;
    }
}

 

上一篇:“造轮运动”之 ORM框架系列(一)~谈谈我在实际业务中的增删改查


下一篇:Es7 JavaApi 常用方法