二叉樹的最近公共祖先

題目:
例如,給定如下二叉樹: root = [3,5,1,6,2,0,8,null,null,7,4]

示例 1:

輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
輸出: 3
解釋: 節(jié)點 5 和節(jié)點 1 的最近公共祖先是節(jié)點 3。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree

思想:
分別找到root到p,q的路徑,返回路徑中最后一個相同的節(jié)點

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.LinkedList;
import java.util.ArrayList;
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(p==null) {
            return q;
        }
        if(q==null) {
            return p;
        }
        ArrayList<TreeNode> res1 = new ArrayList<>();
        getPath(root,p, new LinkedList<>(),res1);
        
        ArrayList<TreeNode> res2 = new ArrayList<>();
        getPath(root,q, new LinkedList<>(),res2);
        
        TreeNode node = null;
        int i = 0;
        while(i<res1.size()&&i<res2.size()) {
            if(res1.get(i)==res2.get(i)) {
                node = res1.get(i);
                i++;
            }else{
                break;
            }
        }
        
        return node;
    }
    
    private void getPath(TreeNode root, TreeNode node, LinkedList<TreeNode> temp, ArrayList<TreeNode> res) {
        if(root==null) {
            return;
        }
        temp.add(root);
        if(root==node) {
            for(int i=0;i<temp.size();i++) {
                res.add(temp.get(i));
            }
            return;
        }
        getPath(root.left,node,temp,res);
        getPath(root.right,node,temp,res);
        temp.pollLast();
    }
    
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容