Daily leetcode_193 nearest common ancestor of binary search tree

Daily leetcode_193 nearest common ancestor of binary search tree

Record your own growth, come on.

Question source:LCR 193. The nearest common ancestor of the binary search tree - LeetCode

topic

Idea:

Solve problems

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;
    }
}

Guess you like

Origin blog.csdn.net/qq_45925197/article/details/133756820