力扣算法学习day11-3

文章目录

  • 力扣算法学习day11-3
    • 226-翻转二叉树
      • 题目
        • 代码实现
    • 101-对称二叉树
      • 题目
      • 代码实现

力扣算法学习day11-3

226-翻转二叉树

题目

力扣算法学习day11-3_第1张图片

力扣算法学习day11-3_第2张图片

代码实现

/**
 * 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 {
    public TreeNode invertTree(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<>();

        if(root == null){
            return root;
        }
        queue.offer(root);
        while(!queue.isEmpty()){
            int len = queue.size();

            while(len > 0){
                TreeNode node = queue.poll();
                TreeNode temp = node.left;
                node.left = node.right;
                node.right = temp;

                if(node.left != null){
                    queue.offer(node.left);
                }

                if(node.right != null){
                    queue.offer(node.right);
                }

                len--;
            }
        }

        return root;
    }
}

101-对称二叉树

题目

力扣算法学习day11-3_第3张图片

力扣算法学习day11-3_第4张图片

代码实现

/**
 * 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 {
    public boolean isSymmetric(TreeNode root) {
        return compare(root.left,root.right);
    }
    // 递归
    public boolean compare(TreeNode left,TreeNode right){
        // 终止条件
        if(left == null && right != null){
            return false;
        } else if(left != null && right == null){
            return false;
        } else if(left == null && right == null){
            return true;
        } else if(left.val != right.val){// 都不为空的情况
            return false;
        }

        // 循环逻辑,都不为空,且值都相同的情况
        boolean wai = compare(left.left,right.right);
        boolean nei = compare(left.right,right.left);

        return nei && wai;
    }
    // 迭代明天再做了,过年耍哈。
}

你可能感兴趣的:(算法刷题,算法,leetcode,java)