ice rabbit programming

[LeetCode] Invert Binary Tree 본문

PS/LeetCode

[LeetCode] Invert Binary Tree

판교토끼 2020. 4. 27. 22:18

https://leetcode.com/problems/invert-binary-tree/

 

Invert Binary Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

이전 문제에서 List를 뒤집었다면 이번에는 Tree를 뒤집는 문제이다. 재귀를 이용해서 left와 right를 뒤집는 로직이다.

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

'PS > LeetCode' 카테고리의 다른 글

[LeetCode] Employees Earning More Than Their Manager  (0) 2020.05.01
[LeetCode] Symmetric Tree  (0) 2020.05.01
[LeetCode] Reverse Linked List  (0) 2020.04.27
[LeetCode] Combine Two Tables  (0) 2020.04.27
[LeetCode] Customers Who Never Order  (0) 2020.04.26