代码随想录算法训练营第15天 | 102.二叉树的层序遍历、226.翻转二叉树、101. 对称二叉树

102.二叉树的层序遍历

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

示例 1:


输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/binary-tree-level-order-traversal

队列存放当前一层二叉树的元素,队列不为空时,记录队列大小size,把队列的前size个元素poll出来,如果该元素的左子树和右子树不为空,加入到队列尾。

public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        if(root==null) return res;
        Queue<TreeNode>queue=new LinkedList<TreeNode>();
        queue.add(root);
        while(!queue.isEmpty()) {
        	int size=queue.size();
        	List<Integer> tres=new ArrayList<>();
        	while(size-->0) {
        		TreeNode cur=queue.poll();
        		tres.add(cur.val);
        		if(cur.left!=null) queue.add(cur.left);
        		if(cur.right!=null) queue.add(cur.right);
        	}
        	res.add(tres);
        }
        return res;
    }

 226.翻转二叉树

给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

示例 1:

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/invert-binary-tree

 按前序遍历节点,每遍历到一个节点,翻转节点的左子树和右子树。

 public TreeNode invertTree(TreeNode root) {
        if(root==null) return null;
        Stack<TreeNode>stack=new Stack<>();
    	stack.add(root);
    	while(!stack.isEmpty()) {
    		TreeNode cur=stack.pop();
    		TreeNode t=cur.left;
    		cur.left=cur.right;
    		cur.right=t;
    		if(cur.right!=null) stack.add(cur.right);
    		if(cur.left!=null) stack.add(cur.left);
    	}
    	return root;
    }

101. 对称二叉树

给你一个二叉树的根节点 root , 检查它是否轴对称。

示例 1:

输入:root = [1,2,2,3,4,4,3]
输出:true

 root的左子树和右子树作为两个树进行对比,对比左子树的左节点和右子树的右节点,以及左子树的右节点和右子树的左节点。

    public boolean isSymmetric(TreeNode root) {
           return compare(root.left,root.right);
    }
    public boolean compare(TreeNode r1,TreeNode r2) {
    	if(r1==null&&r2==null) return true;
    	else if(r1==null&&r2!=null) return false;
    	else if(r1!=null&&r2==null) return false;
    	else if(r1.val!=r2.val) return false;
    	return compare(r1.left,r2.right)&&compare(r1.right,r2.left);
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值