LeetCode:226翻转二叉树

方法一:递归法

java 复制代码
/**
 * 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) {
        if(root == null){
            return null;
        }
        //左右节点交换
        TreeNode temp = root.right;
        root.right = root.left;
        root.left = temp;
        //递归左右节点
        invertTree(root.left);
        invertTree(root.right);

        return root;
    }
}

方法二:

java 复制代码
/**
 * 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){
        if(root == null){
            return null;
        }

        Queue<TreeNode> queue = new LinkedList<>();

        queue.offer(root);

        while(!queue.isEmpty()){
            TreeNode current = queue.poll();
            //交换左右节点
            TreeNode temp = current.left;
            current.left = current.right;
            current.right = temp;

            //左右节点不为空则入队
            if(current.left != null){
                queue.offer(current.left);
            }
            if(current.right != null){
                queue.offer(current.right);
            }
        } 
        return root;
    }
 }

迭代法思路:

先将根节点入队

while循环,只要队列不为空就交换当前要出队节点的左右节点,然后判断当前出队节点的下面是否还有左右节点,如果有就继续入队,循环。

爆栈,层序遍历,逐层打印。寻找最短路径使用队列;核心:new Queue -> offer(root) -> while(!isEmpty) -> poll() -> 处理逻辑 -> offer(children)

相关推荐
wabs66620 分钟前
关于图论【A*算法 | 卡码网127.骑士的攻击的思考】
数据结构·算法·图论·卡码网·广搜的改进版
CIO_Alliance28 分钟前
AI认知系列(3)| 数据、算法、算力、场景四要素协同
人工智能·算法·ipaas·系统集成·企业cio联盟·企业级ai化转型
凉茶钱30 分钟前
【数据结构】堆的应用
c语言·数据结构
Forever Nore1 小时前
LeetCode 13 罗马数字转整数 - 按规则处理
linux·服务器·leetcode
..Dauntless..2 小时前
手写vector vs std::vector:从功能正确到性能达标
算法
间歇性努力持续性发呆的野生快乐选手2 小时前
栈的性质(进栈,出栈,访问)
数据结构·c++
m0_547486662 小时前
《数据结构与算法》全套PPT课件2026(中国海洋大学)
数据结构·算法
旖旎夜光2 小时前
LeetCode 904:水果成篮(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
怪奇云呼军3 小时前
G.711、Opus 和重采样会拖慢识别吗?闪电智能VoiceAgent 的音频入口怎么选
java·人工智能·python·算法·云计算·音视频
ZC跨境爬虫3 小时前
LeetCode 27. 移除元素(双指针详解 + Java Python 多解法对比)
java·python·leetcode