代码随想录训练营day15|102、层序遍历;226、翻转二叉树;101、对称二叉树 2

102、层序遍历

class Solution {
    public List> levelOrder(TreeNode root) {
        List> resList = new ArrayList>();

        if(root == null){
            return resList;
        }

        //队列
        Queue que = new LinkedList();
        que.offer(root);

        while(!que.isEmpty()){
            // 结果列表
            List itemList = new ArrayList();
            int len = que.size();

            while(len>0){
                TreeNode tmpNode = que.poll();
                itemList.add(tmpNode.val);

                if (tmpNode.left != null){
                    que.offer(tmpNode.left);
                }
                if (tmpNode.right != null){
                    que.offer(tmpNode.right);
                }
                len--;
            }
        resList.add(itemList);
        }
        return resList;
    }
}

使用队列即可。注意要记录每次有多少个节点出队。

226、翻转二叉树

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null){
            return null;
        }
        swapChildren(root);
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    private void swapChildren(TreeNode root){
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
    }
}

101、对称二叉树 2

class Solution {
    public boolean isSymmetric(TreeNode root) {
        return compare(root.left, root.right);
    }

    private boolean compare(TreeNode left, TreeNode right){
        if(left == null && right == null) return true;
        else if(left == null && right != null) return false;
        else if(left != null && right == null) return false;
        else if(left.val != right.val) return false;

        boolean compareOutside = compare(left.left, right.right);
        boolean compareInside = compare(left.right, right.left);
        return compareOutside && compareInside;
    }
}

递归三步曲:

1、确定递归函数的参数和返回值

2、确定终止条件

3、确定单层递归的逻辑

你可能感兴趣的:(leetcode,算法,职场和发展)