【LeetCode每日一题】226. 翻转二叉树

【LeetCode每日一题】226. 翻转二叉树

226. 翻转二叉树

题目来源link
算法思想:递归;树;

树形结构要求翻转如下:
翻转要求

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) {
    
    
        invert(root);
        return root;
    }

    public void invert(TreeNode root){
    
    //图形要求,先序遍历二叉树,翻转
        if(root == null){
    
    
            return;
        }
        //先序遍历:根(操作),左,右
        TreeNode temp = new TreeNode();
        temp = root.left;
        root.left = root.right;
        root.right = temp;
        invert(root.left);
        invert(root.right);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39457586/article/details/108615591