【LeetCode】【HOT】236. 二叉树的最近公共祖先(递归)

【LeetCode】【HOT】236. 二叉树的最近公共祖先

文章目录

  • 【LeetCode】【HOT】236. 二叉树的最近公共祖先

【LeetCode】【HOT】236. 二叉树的最近公共祖先(递归)_第1张图片
【LeetCode】【HOT】236. 二叉树的最近公共祖先(递归)_第2张图片

package hot;

class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int val){
        this.val = val;
    }
}

public class Solution236 {
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(3);
        TreeNode node2 = new TreeNode(5);
        TreeNode node3 = new TreeNode(1);
        TreeNode node4 = new TreeNode(6);
        TreeNode node5 = new TreeNode(2);
        TreeNode node6 = new TreeNode(0);
        TreeNode node7 = new TreeNode(8);
        TreeNode node8 = new TreeNode(7);
        TreeNode node9 = new TreeNode(4);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node6;
        node3.right = node7;
        node5.left = node8;
        node5.right = node9;
        Solution236 solution = new Solution236();
        System.out.println(solution.method(node1, node2, node9).val);
    }

    private TreeNode method(TreeNode root, TreeNode p, TreeNode q){
        if(root == null || root == p || root == q){
            return root;
        }
        TreeNode left = method(root.left, p, q);
        TreeNode right = method(root.right, p, q);
        if(left == null && right == null) return null;
        if(left == null) return right;
        if(right == null) return left;
        return root;
    }
}

//时间复杂度为 O(n)
//空间复杂度为 O(n)

你可能感兴趣的:(LeetCode,LeetCode)