每日leetcode_193二叉搜索树的最近公共祖先

每日leetcode_193二叉搜索树的最近公共祖先

记录自己的成长,加油。

题目出处:LCR 193. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)

题目

每日leetcode_193二叉搜索树的最近公共祖先_第1张图片

每日leetcode_193二叉搜索树的最近公共祖先_第2张图片

思路:

每日leetcode_193二叉搜索树的最近公共祖先_第3张图片

解题

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        List<TreeNode> path_p = getPath(root, p);
        List<TreeNode> path_q = getPath(root, q);
        TreeNode ancestor = null;
        for (int i = 0; i < path_p.size() && i < path_q.size(); ++i) {
            if (path_p.get(i) == path_q.get(i)) {
                ancestor = path_p.get(i);
            } else {
                break;
            }
        }
        return ancestor;
    }

    public List<TreeNode> getPath(TreeNode root, TreeNode target) {
        List<TreeNode> path = new ArrayList<TreeNode>();
        TreeNode node = root;
        while (node != target) {
            path.add(node);
            if (target.val < node.val) {
                node = node.left;
            } else {
                node = node.right;
            }
        }
        path.add(node);
        return path;
    }
}

你可能感兴趣的:(LeetCode算法学习,leetcode,算法,职场和发展)