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

    二叉树最近祖先,使用递归方法,满足左子树和右子树都找到,或者某一个节点作为根结点而它的子节点包含另一个目标节点

    class Solution {
        TreeNode* ancestor;
        bool find_ancestor = false;
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            searchNodes(root, p, q);
            return ancestor;
        }
    
        bool searchNodes(TreeNode* root, TreeNode* p, TreeNode* q) {
            if (root == nullptr) {
                return false;
            }
            bool lson = searchNodes(root->left, p, q);
            bool rson = searchNodes(root->right, p, q);
    
            if ((lson && rson) || ((root == p || root == q) && (lson || rson))) {
                ancestor = root;
                return false;
            }
    
            return lson || rson || root == p || root == q;
        }
    };
    

      

  • 相关阅读:
    Qt之Threads和QObjects
    Qt之可重入与线程安全
    Qt之线程基础
    Qt之QLineEdit
    Qt之属性系统
    Django框架
    web框架起源
    django查看数据库
    jQuery
    BOM&DOM
  • 原文地址:https://www.cnblogs.com/rulin/p/14055142.html
Copyright © 2011-2022 走看看