二叉树-Lowest Common Ancestor

来源:互联网 发布:禁止ip访问http linux 编辑:程序博客网 时间:2024/04/28 19:52

1. Binary search tree:只需要判断当前node值是否在两个node之间

2. Binary tree with parent link:先求两个node的height, 然后向上traverse

3. Binary tree without parent link:

solution 1: top-bottom

int countMatches(TreeNode root, TreeNode p, TreeNode q) {if (root == null) {return 0;}int matches = countMatches(root.left, p, q) + countMatches(root.right, p, q);if (root == p || root == q) {return matches + 1;} else {return matches;}}TreeNode findLCA(TreeNode root, TreeNode p, TreeNode q) {if (root == null || p == null || q == null) {return null;}int matches = countMatches(root, p, q);if (matches == 1) {return root;}if (matches == 2) {return findLCA(root.left, p, q);} else {return findLCA(root.right, p, q);}}

Solution 2: bottom-top

TreeNode findLCA2(TreeNode root, TreeNode p, TreeNode q) {if (root == null) {return null;}if (root == p || root == q) {return root;}TreeNode left = findLCA2(root.left, p, q);TreeNode right = findLCA2(root.right, p, q);if (left != null && right != null) { // 左边和右边分别含有p,qreturn root;}return left == null ? right : left;}


0 0
原创粉丝点击