Problem : https://leetcode.com/problems/invert-binary-tree/
Invert the tree recursively.
/**
* 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) {
return root != null ?
new TreeNode(root.val, invertTree(root.right), invertTree(root.left))
: null;
}
}
Updated on 02/17/2023. Replaced with a Java solution.
No comments:
Post a Comment