LeetCode-剣はオファーを指します:バイナリツリーの最も近い共通の祖先Ⅱ

バイナリツリーIIの最も近い共通の祖先(単純)

2020年9月18日

質問元:Likou
ここに写真の説明を挿入

問題解決

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    
    
        //树为空直接返回
        if(root==null) return null;
        //如果有一个等于root,直接返回
        if(root==p ||root==q) return root;
        //遍历左子树
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        //遍历右子树
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        //左子树为空,一定在右子树上
        if(left==null) return right;
        //右子树为空,一定在左子树上
        else if(right==null) return left;
        //都不为空就是根节点了
        else return root;
    }
}

ここに写真の説明を挿入

おすすめ

転載: blog.csdn.net/weixin_41541562/article/details/108658120