求二叉树的两个节点的最近公用先祖

My first Leetcode code.


/**

* Definition for a binary tree node.

* struct TreeNode {

*    int val;

*    TreeNode *left;

*    TreeNode *right;

*    TreeNode(int x) : val(x), left(NULL), right(NULL) {}

* };

*/

#define max(val1, val2)  (val1 > val2 ? val1 : val2)

#define min(val1, val2)  (val1 < val2 ? val1 : val2)

class Solution {

public:

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {

if (root == nullptr || p == nullptr || q == nullptr ) return nullptr;

if (max(p->val, q->val) < root->val)

return lowestCommonAncestor(root->left, p, q);

else if (min(p->val, q->val) > root->val)

return lowestCommonAncestor(root->right, p, q);

else

return root;

}

};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • --- knowledge ---# of leaves = # of nonleaves + 1 - Bi...
    陈十十阅读 303评论 0 0
  • 上次写了二叉树遍历,其中在非递归的遍历中,只写了前序遍历,没有写非递归中序遍历和后续遍历。非递归要用到栈,只要根据...
    BrianAguilar阅读 468评论 0 1
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 2,046评论 0 2
  • 树的代码 101. Symmetric Tree Given a binary tree, check wheth...
    lindsay_bubble阅读 486评论 0 0
  • 姓名: 李小娜 [嵌牛导读] :这篇文章主要介绍了Java二叉排序树,包括二叉排序树的定义、二叉排序树的性质、二叉...
    n184阅读 641评论 0 0