LeetCode226. 翻转二叉树

思路

就是遍历二叉树的每个节点,将节点的左右孩子交换就好了。比较简单。

代码

/**
 * 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;
        }
        TreeNode temp = root;
        fun(temp);
        return root;
        

    }
    public void fun(TreeNode root){
        if(root==null){
            return;
        }else{
            TreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
            fun(root.left);
            fun(root.right);
        }
        
    }
}

你可能感兴趣的:(LeetCode,leetcode,二叉树)