Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:网络爬虫 登陆 编辑:程序博客网 时间:2024/05/29 06:42
情况一:节点只有左、右指针,root已知
情况二: 二叉树是个二叉查找树,且root和两个节点的值(a, b)已知
思路:一开始想到用递归去做,但是因为本来对递归的概念还很模糊,所以在设计递归出口的时候一点思路也没有,翻了关于递归的资料,找到一张图能很好地解释递归:
递归有两个出口,一是没有找到a或者b,则返回NULL;二是只要碰到a或者b,就立刻返回,这样的话下面的代码就很好理解了。- // 二叉树结点的描述
- typedef struct BiTNode
- {
- char data;
- struct BiTNode *lchild, *rchild; // 左右孩子
- }BinaryTreeNode;
- // 节点只有左指针、右指针,没有parent指针,root已知
- BinaryTreeNode* findLowestCommonAncestor(BinaryTreeNode* root , BinaryTreeNode* a , BinaryTreeNode* b)
- {
- if(root == NULL)
- return NULL;
- if(root == a || root == b)
- return root;
- BinaryTreeNode* left = findLowestCommonAncestor(root->lchild , a , b);
- BinaryTreeNode* right = findLowestCommonAncestor(root->rchild , a , b);
- if(left && right)
- return root;
- return left ? left : right;
- }
情况二: 二叉树是个二叉查找树,且root和两个节点的值(a, b)已知
- // 二叉树是个二叉查找树,且root和两个节点的值(a, b)已知
- BinaryTreeNode* findLowestCommonAncestor(BinaryTreeNode* root , BinaryTreeNode* a , BinaryTreeNode* b)
- {
- char min , max;
- if(a->data < b->data)
- min = a->data , max = b->data;
- else
- min = b->data , max = a->data;
- while(root)
- {
- if(root->data >= min && root->data <= max)
- return root;
- else if(root->data < min && root->data < max)
- root = root->rchild;
- else
- root = root->lchild;
- }
- return NULL;
- }
0 0
- Lowest Common Ancestor of a Binary Search Tree
- leetcode 235: Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree (235)
- Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree leetcode235
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree
- leetcode: Lowest Common Ancestor of a Binary Search Tree
- [leetcode][dfs] Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235.Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】235 Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235.Lowest Common Ancestor of a Binary Search Tree
- leetcode 235 Lowest Common Ancestor of a Binary Search Tree
- [leetcode] Lowest Common Ancestor of a Binary Search Tree
- 深入理解RunLoop
- Bootmem机制
- Qt学习之路(17): Qt标准对话框之QMessageBox
- VS2012通过ASO.NET实体模型添加oracle数据库连接
- 数据库
- Lowest Common Ancestor of a Binary Search Tree
- HDU1241 深搜
- NYOJ Rectangles--1255第七届
- 机房收费系统总结篇(一)
- linux内核打补丁步骤
- 项目36-数组类运算的实现
- poj 2823 Sliding Window
- 如何对齐多个对象
- UIView