Java - Very simple & basic recursion


  • 0
    T

    This probably doesn't even need a explanation. Very simple and basic bottom up recursion.

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

  • 0
    K

    Came out with similar solution

    public class Solution {
        public TreeNode invertTree(TreeNode root) {
            if (root == null)
    		return null;
    	TreeNode left = invertTree(root.left);
    	TreeNode right = invertTree(root.right);
    	root.left = right;	
    	root.right = left;
    	return root;
        }
    }
    

  • 0
    M
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.