标签:
1 //查找一棵树中最近公共父节点 2 public class LCA { 3 static boolean flag[] = new boolean[2];; 4 5 public static TreeNode findLowestCommonAncestor(TreeNode head, TreeNode first, TreeNode second){ 6 travel(head, first, second); 7 if(flag[0] == true && flag[1] == true) // 两节点都存在 8 return lowestCommonAncestor(head, first, second); 9 else 10 return null; 11 } 12 13 public static void travel(TreeNode head, TreeNode first, TreeNode second) { 14 if(head == null) 15 return; 16 17 if(head.value == first.value) 18 flag[0] = true; 19 if(head.value == second.value) 20 flag[1] = true; 21 travel(head.left, first, second); 22 travel(head.right, first, second); 23 } 24 25 public static TreeNode lowestCommonAncestor(TreeNode head, TreeNode first, TreeNode second) { 26 if (head == null) 27 return null; 28 29 // 先根遍历 30 if (head.value == first.value || head.value == second.value) 31 return head; 32 TreeNode left = lowestCommonAncestor(head.left, first, second); 33 TreeNode right = lowestCommonAncestor(head.right, first, second); 34 if ((left != null) && (right != null)) { 35 return head; 36 } 37 return left != null ? left : right; 38 } 39 40 public static void main(String[] args) { 41 TreeNode node1 = new TreeNode(1); 42 TreeNode node2 = new TreeNode(2); 43 TreeNode node3 = new TreeNode(3); 44 TreeNode node4 = new TreeNode(4); 45 TreeNode node5 = new TreeNode(5); 46 TreeNode node6 = new TreeNode(6); 47 TreeNode node7 = new TreeNode(7); 48 node1.left = node2; 49 node1.right = node3; 50 node2.left = node4; 51 node2.right = node5; 52 node4.right = node6; 53 TreeNode result = findLowestCommonAncestor(node1, node6, node5); // 2 54 // TreeNode result = findLowestCommonAncestor(node1, node1, node2); // 1 55 // TreeNode result = findLowestCommonAncestor(node1, node1, node7); // null 56 57 System.out.println(result != null ? result.value : result); 58 } 59 } 60 61 class TreeNode { 62 TreeNode left; 63 TreeNode right; 64 int value; 65 66 TreeNode(int value) { 67 this.value = value; 68 } 69 }
标签:
原文地址:http://www.cnblogs.com/shake-rock/p/5497195.html