Bootstrap

力扣算法学习day11-3

力扣算法学习day11-3

226-翻转二叉树

题目

image-20220131201300556

image-20220131201327822

代码实现
/**
 * 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-对称二叉树

题目

image-20220131223321803

image-20220131223414260

代码实现

/**
 * 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;
    }
    // 迭代明天再做了,过年耍哈。
}
;