LeetCode 235. Lowest Common Ancestor of a Binary Search Tree

来源:互联网 发布:像牲口一样活下去 知乎 编辑:程序博客网 时间:2024/05/13 15:55

描述

BST中找最近公共父节点

解决

递归搜索


/** * 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 (!root)            return NULL;        else if (root -> val > p -> val && root -> val > q -> val)            return lowestCommonAncestor(root -> left, p, q);        else if (root -> val < p -> val && root -> val < q -> val)            return lowestCommonAncestor(root -> right, p, q);        else            return root;    }};
0 0
原创粉丝点击