↓ Skip to main content
  1. Posts/

leetcode 235. Lowest Common Ancestor of a Binary Search Tree(求一个BST中某两个节点LCA)

·371 words·1 min
Note: This article is available in Chinese only. 本文暂无英文版本。 View original

题目链接

题意:求一个BST中某两个节点LCA….

思路:卧槽。。。竟然求LCA…直接想到的显然是Tarjan的方法或者。。。RMQ+DFS。。。但是感觉。。。leetcode怎么可能考算法。。。。于是想到。。。可以从BST下手。。。

两个节点的LCA的值一定在这两个节点之间。

可以根据这个条件做二分。。。

这道题的收获是。。。不要被已知的东西限制住思路。。。tarjan或者RMQ+DFS显然也能做。。。但是那样的相当于没有用到BST的条件。。。

 1/**
 2 * Definition for a binary tree node.
 3 * struct TreeNode {
 4 *     int val;
 5 *     TreeNode *left;
 6 *     TreeNode *right;
 7 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8 * };
 9 */
10class Solution {
11public:
12        TreeNode * Find(TreeNode* root,TreeNode* p,TreeNode *q)
13        {
14            if (root==NULL) return NULL; //实际上这应该不可能发生》。。。
15            int rt = root->val;
16            int a = p->val;
17            int b = q->val;
18            if (a<=rt&&rt<=b) return root;
19            if (b<=rt&&rt<=a) return root;
20            if (a<rt&&b<rt) return Find(root->left,p,q);
21            if (a>rt&&b>rt) return Find(root->right,p,q);
22        }
23    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
24        if (root==NULL) return NULL;
25        TreeNode* res = Find(root,p,q);
26        return res;
27    }
28};

Related

leetcode 104. Maximum Depth of Binary Tree(求一棵树的深度)

·158 words·1 min
题目链接 题意:求一棵树的深度。。。。 思路:。。。定义搞即可。。按照左右子树中大的算。。。因为据说是经典题(虽然并不觉得2333。。。所以记录下。。。 1/** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10class Solution { 11public: 12 13 int dfs(TreeNode* root) 14 { 15 if (root==NULL) return 0; 16 return max(dfs(root->left),dfs(root->right))+1; 17 } 18 19 int maxDepth(TreeNode* root){ 20 if (root==NULL) return 0; 21 int res = dfs(root); 22 return res; 23 24 25 } 26};

leetcode 226. Invert Binary Tree(反转二叉树)

·208 words·1 min
题目链接 题意:反转一棵二叉树。。。字面意思理解即可。。就是把每一棵子树的左右孩子交换。。。 思路:直接照着题意做就好了。。。没有坑。。记录的原因是听说这题比较经典(虽然毫无难度…

112. Path Sum

·257 words·1 min
题目链接 题意:给一棵树。。问是否存在一条从树根到叶子的路径,使得路径上每个点的val之和等于给定的sum。 思路:。。。直接搞就好。。。由于是比较经典的题目所以记录一下。。。注意递归的时候每一部分都要返回值orz..(我是多久没写代码了。。。