本文主要是介绍Binary Tree - Lowest Common Ancestor 题型总结,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Lowest Common Ancestor of a Binary Search Tree
思路:这题跟 Lowest Common Ancestor of Binary Tree 一模一样。思路:就是找p的节点在不在左支,或者右支,找到各自左右节点,然后进行比较,如果两者不一样,说明当前的root就是lowest 父节点,如果左边为空,那就都在右边,返回右边的即可,如果右边为空,那就都在左边,返回左边的即可。
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if(root == null) {return null;}if(p == null || q == null) {return root;}TreeNode node = root;while(node != null) {if(node.val < p.val && node.val < q.val) {node = node.right;} else if(node.val > p.val && node.val > q.val) {node = node.left;} else {break;}}return node;}
}
Lowest Common Ancestor of a Binary Tree
思路:lowestCommonAncestor 的定义就是找到的LCA;
如果两者都不为空,说明当前的root就是lowest 父节点,如果左边为空,那就都在右边,返回右边的即可,如果右边为空,那就都在左边,返回左边的即可。
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if(root == null || root == p || root == q) {return root;}TreeNode leftnode = lowestCommonAncestor(root.left, p, q);TreeNode rightnode = lowestCommonAncestor(root.right, p, q);if(leftnode == null) {return rightnode;} else if(rightnode == null) {return leftnode;} else {return root;}}
}
Lowest Common Ancestor of Deepest Leaves
- 题目要求求deepest leaf的LCA,我们首先需要tree depth的信息(注意不是node depth, 也可以理解为deepest leaf depth 也就是tree depth信息),然后跟LCA一样,需要返回node信息,那么我们就需要resultType作为返回值;findLCA 表示当前枝,找到的LCA和它所能找到的deepest leaf 的depth;如果左右depth相等,证明当前node就是LCA;并返回leftnode的depth也就是deepest node的depth;
注意这里有两个表示:一个是method的depth代表node的depth,另外一个returnType里面的depth代表找到的node的 deepest depth;
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {private class ReturnType {public TreeNode node;public int depth;public ReturnType(TreeNode node, int depth) {this.node = node;this.depth = depth;}}public TreeNode lcaDeepestLeaves(TreeNode root) {if(root == null) {return null;}ReturnType n = findLCA(root, 0);return n.node;}private ReturnType findLCA(TreeNode root, int depth) {if(root == null) {return new ReturnType(null, depth);}ReturnType leftnode = findLCA(root.left, depth + 1);ReturnType rightnode = findLCA(root.right, depth + 1);if(leftnode.depth == rightnode.depth) {return new ReturnType(root, leftnode.depth);}if(leftnode.depth > rightnode.depth) {return leftnode;} else {return rightnode;}}
}
这篇关于Binary Tree - Lowest Common Ancestor 题型总结的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!