代码随想录第15天: 二叉树part02

力扣102 二叉树的层序遍历

class Solution {

    public List<List<Integer>> reslist = new ArrayList<List<Integer>>();

    public List<List<Integer>> levelOrder(TreeNode root) {
        checkfun(root);
        return reslist;
    }

    public void checkfun(TreeNode root) {
        if(root == null) return;
        Queue<TreeNode> nodeque = new LinkedList<TreeNode>();
        int len = 1;
        nodeque.offer(root);
        while(!nodeque.isEmpty()) {
            List<Integer> itemlist = new ArrayList<>();
            while(len > 0) {
                TreeNode tmpnode = nodeque.poll();
                itemlist.add(tmpnode.val);
                if(tmpnode.left != null) nodeque.offer(tmpnode.left);
                if(tmpnode.right != null) nodeque.offer(tmpnode.right);
                len--;
            }
            len = nodeque.size();
            reslist.add(itemlist);
        }
    }
}

力扣226 翻转二叉树

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

力扣101 对称二叉树

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 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 outside = compare(left.left, right.right);
        boolean inside = compare(left.right, right.left);
        return outside && inside;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值