LeetCode:翻转二叉树【226】

LeetCode:翻转二叉树【226】

题目描述

翻转一棵二叉树。

示例:

输入:

     4
   /   
  2     7
 /    / 
1   3 6   9

输出:

     4
   /   
  7     2
 /    / 
9   6 3   1

题目分析

  略。

Java题解

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null)
            return null;
        return DFS(root);
    }

    public TreeNode DFS(TreeNode node){
        TreeNode tmp = node.right;
        node.right=node.left;
        node.left=tmp;
        if(node.left!=null)
            DFS(node.left);
        if(node.right!=null)
            DFS(node.right);
        return node;
    }
}

  

原文地址:https://www.cnblogs.com/MrSaver/p/9953147.html