力扣226.翻转二叉树(java)

题目来源

226. 翻转二叉树 - 力扣(LeetCode)

代码(dfs)

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 root;

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);

        while(!stack.isEmpty()) {
            TreeNode node = stack.pop();

            if(node.right != null) stack.push(node.right);
            if(node.left != null) stack.push(node.left);

            swapNode(node);
        }
        return root;
    }
    //交换某结点左右子树
    private void swapNode(TreeNode node) {
        TreeNode tmp = node.left;
        node.left = node.right;
        node.right = tmp;
    }

}

代码分析

直接正常入栈就行,把栈顶结点直接交换左右子树就行。也就是,从根节点开始,交换左右子树,然后左节点,最后右结点。

相关推荐
Navigator_Z9 分钟前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.13 分钟前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好38 分钟前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法
All for pursuit.39 分钟前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
wzdark1 小时前
数据压缩算法的时间复杂度与压缩率权衡4
算法
yuanxi2001 小时前
卡塔尔能源公司LNG扩建项目首条生产线预计明年投运:大客户销售的5个判断
职场和发展·创业创新·学习方法
小陈phd1 小时前
深入理解agent学习笔记(一)——现代agent介绍
人工智能·算法
圣保罗的大教堂1 小时前
leetcode 1665. 完成所有任务的最少初始能量 中等
leetcode
晴天的雨.9924 小时前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
aramae11 小时前
MySQL复合查询(8)
java·c语言·开发语言·后端·算法