力扣每日一题:2415. 反转二叉树的奇数层(2023-12-15)

2023-12-15 10:57:11

力扣每日一题
题目:2415. 反转二叉树的奇数层
2023-12-15.png
日期:2023-12-15
用时:6 m 51 s
时间:0 ms
内存:46.97 MB
代码:

/**
 * 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 reverseOddLevels(TreeNode root) {
        dfs(root.left, root.right, 1);
        return root;
    }

    void dfs(TreeNode left,TreeNode right,int odd){
        if(left==null){
            return;
        }
        if(odd==1){
            int temp = left.val;
            left.val = right.val;
            right.val = temp;
        }
        dfs(left.left, right.right, 1-odd);
        dfs(left.right, right.left, 1-odd);
    }
}

文章来源:https://blog.csdn.net/huangge1199/article/details/135009530
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。