首页 > 其他分享 >【leetcode】226.翻转二叉树

【leetcode】226.翻转二叉树

时间:2023-03-16 23:36:50浏览次数:50  
标签:right TreeNode leetcode 二叉树 226 root public left

翻转二叉树

leetcode题目传送门

  1. 题目描述

    翻转二叉树

  2. 思路

    按顺序依次交换二叉树的左右节点

  3. 实现

    交换左右节点,递归遍历


public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
       this.val = val;
         this.left = left;
         this.right = right;
     }
 }

public class Solution {
    public TreeNode InvertTree(TreeNode root) {
        if(root==null){
            return null;
        }

        // 暂存,左右交换,通过递归实现子节点的自己交换
        TreeNode temp = root.left;

        root.left=InvertTree(root.right);

        root.right=InvertTree(temp);

        return root;

    }

}



标签:right,TreeNode,leetcode,二叉树,226,root,public,left
From: https://www.cnblogs.com/thomerson/p/17224642.html

相关文章