Lowest Common Ancestor of Binary Search Tree (BST)
2013-09-09 22:12
190 查看
Given a binary search tree (BST), find the lowest common ancestor of two given nodes in the BST.
Thoughts:
1. 两个节点在同一个子树(左子树,右子树), recursive搜索
2. 不在同一个子树,当下的根节点就是他们的共同节点
Solution:
Thoughts:
1. 两个节点在同一个子树(左子树,右子树), recursive搜索
2. 不在同一个子树,当下的根节点就是他们的共同节点
Solution:
Node* findLCA(Node *tree, Node *n1, Node *n2) { if(!tree || !n1 || !na) return NULL; else if (max(n1->val, n2->val) > tree->val) findLCA(tree->right, n1, n2); else if(min(n1->val, n2->val) < tree->val) findLCA(tree->left, n1, n2); else return tree; }
相关文章推荐
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树BST的最近公共祖先LCA + 深度优先遍历DFS
- 72【leetcode】经典算法- Lowest Common Ancestor of a Binary Search Tree(lct of bst)
- 72【leetcode】经典算法- Lowest Common Ancestor of a Binary Search Tree(lct of bst)
- Lowest Common Ancestor of a Binary Search Tree (BST)
- 72【leetcode】经典算法- Lowest Common Ancestor of a Binary Search Tree(lct of bst)
- My Solution to Lowest Common Ancestor of a Binary Search Tree (BST)
- 72【leetcode】经典算法- Lowest Common Ancestor of a Binary Search Tree(lct of bst)
- 72【leetcode】经典算法- Lowest Common Ancestor of a Binary Search Tree(lct of bst)
- Lowest Common Ancestor of a Binary Search Tree (BST)
- LeetCode:Lowest Common Ancestor of a Binary Search Tree(BST最近公共祖先)
- 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[235]:Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 15算法课程 235. Lowest Common Ancestor of a Binary Search Tree
- [leetcode-235]Lowest Common Ancestor of a Binary Search Tree(C)
- [leetcode] 235. 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