Sword refers to Offer ------- the nearest common ancestor of the binary tree

Insert picture description here
Topic link!

Idea:
Insert picture description here
From here, please click!

In this case, using dfs to search is actually searching the entire tree (except for subtrees below the p and q nodes, there is no search, even if you find the nearest common ancestor of p, q in the left subtree of a certain root, it Will still search the right side of root)

Code:

class Solution {
    
    
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    
    
        if(root == null || root == p || root == q) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if(left == null && right == null) return null; // 1.
        if(left == null) return right; // 3.
        if(right == null) return left; // 4.
        return root; // 2. if(left != null and right != null)
    }
}

Nearest common ancestor of binary search tree

Insert picture description here

Idea: This
question is simpler than the previous question, because it is a binary search tree, which is regular, (here we assume that p->val is smaller than q->val). The node is the nearest common ancestor of these two nodes, so its premise is that the val of the root of a certain subtree is larger than p->val and smaller than q->val. Otherwise, just look at which branch subtree to go. Look at the code specifically.
Insert picture description here

Code:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    
    
        if(p->val > q->val) swap(p,q);

        while(root!=NULL){
    
    
            if(root->val < p->val)  root = root->right;
            else if(root->val > q->val) root = root->left;
            else break;
        }
        return root;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/115262098