zoukankan      html  css  js  c++  java
  • 二叉树最近公共祖先

    思路:后序遍历

    分情况讨论:

    1、两个节点在根的左侧

    2、两个节点在根的右侧

    3、两个节点在根的左右两侧

    /**
     * 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==q||root==p||root == null) return root;//找到或者没找到都进行返回继续递归
            TreeNode l = lowestCommonAncestor(root.left,p,q);
            TreeNode r = lowestCommonAncestor(root.right,p,q);
            if(l==null) return r;//两个节点都不在左子树
            if(r==null) return l;//两个节点都不在右子树
            return root;//两个节点一左一右
        }
    }
    
    
    不一样的烟火
  • 相关阅读:
    20210420
    20210419
    2021041601
    20210416
    20210415
    20210414
    20210413
    20210412
    20210409
    20210405
  • 原文地址:https://www.cnblogs.com/cstdio1/p/13367727.html
Copyright © 2011-2022 走看看