leetcode 226 翻转一棵二叉树

技术文章 1年前 (2020) 完美者
1,174 0

标签:let   ack   print   sys   exe   leetcode   int   rip   treenode   

package com.example.lettcode.dailyexercises;

/**
 * @Class InvertTree
 * @Description 226
 * 翻转一棵二叉树。
 * <p>
 * 示例:
 * 输入:
 * ****   4
 * **  /    * ** 2     7
 * * / \   /  * *1   3 6   9
 * <p>
 * 输出:
 * *       4
 * *    /    * *   7     2
 * * / \   /  * 9   6 3   1
 * @Author
 * @Date 2020/9/16
 **/
public class InvertTree {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public static TreeNode invertTree(TreeNode root) {
        if (root == null) return root;
        dfs(root);
        return root;
    }

    public static TreeNode dfs(TreeNode root) {
        if (root == null) return root;
        TreeNode rightTreeNode = dfs(root.right);
        TreeNode leftTreeNode = dfs(root.left);
        root.left = rightTreeNode;
        root.right = leftTreeNode;
        return root;
    }


    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        TreeNode treeNode1 = new TreeNode(2);
        TreeNode treeNode2 = new TreeNode(7);
        root.left = treeNode1;
        root.right = treeNode2;
        TreeNode treeNode3 = new TreeNode(1);
        TreeNode treeNode4 = new TreeNode(3);
        treeNode1.left = treeNode3;
        treeNode1.right = treeNode4;
        TreeNode treeNode5 = new TreeNode(6);
        TreeNode treeNode6 = new TreeNode(9);
        treeNode2.left = treeNode5;
        treeNode2.right = treeNode6;
        TreeNode treeNode = invertTree(root);
        System.out.println(treeNode);
    }
}

leetcode 226 翻转一棵二叉树

标签:let   ack   print   sys   exe   leetcode   int   rip   treenode   

原文地址:https://www.cnblogs.com/fyusac/p/13679116.html

版权声明:完美者 发表于 2020-09-18 3:02:57。
转载请注明:leetcode 226 翻转一棵二叉树 | 完美导航

暂无评论

暂无评论...