leetcode 235. Lowest Common Ancestor of a Binary Search Tree

来源:互联网 发布:算法分析导论 英文版 编辑:程序博客网 时间:2024/05/16 17:59
/** * 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) {        int a1 = p->val,a2 = q->val;        if(a1 > a2) swap(a1,a2);        while(1){            if(root->val < a1) root = root->right;            else if(root->val > a2)root = root->left;            else return root;        }    }};

0 0
原创粉丝点击