二叉树最近公共父节点

有一个普通二叉树,AB分别为两个子节点,求AB最近的公共父节点。

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 
 5 public class Node {
 6 
 7     Node leftChild;
 8     Node rightChild;
 9     int data;
10     
11     public Node(Node leftChild,Node rightChild,int data){
12         this.leftChild = leftChild;
13         this.rightChild = rightChild;
14         this.data = data;
15     }
16     
17     public boolean getPath(Node root,Node decNode,List<Node> array){
18         boolean findResult = false;
19         if(null != root){
20             if(root == decNode){
21                 array.add(root);
22                 findResult = true;
23             }
24             if(!findResult&& root.leftChild!=null){
25                 findResult = this.getPath(root.leftChild, decNode, array);
26                 if(findResult){
27                     array.add(root);
28                 }
29             }
30             if(!findResult&& root.rightChild!=null){
31                 findResult = this.getPath(root.rightChild, decNode, array);
32                 if(findResult){
33                     array.add(root);
34                 }
35             }
36         }
37         return findResult;
38     }
39     
40     static Node getCommonRoot(Node root,Node a,Node b){
41         Node common = null;
42         List<Node> pathA = new ArrayList<Node>();
43         List<Node> pahtB = new ArrayList<Node>();
44         a.getPath(root, a, pathA);
45         b.getPath(root, b, pahtB);
46         for(Node NodeA:pathA){
47             for(Node NodeB:pahtB){
48                 if(NodeA == NodeB){
49                     common = NodeA;
50                     break;
51                 }
52             }
53             if(null!=common){
54                 break;
55             }
56         }
57         return common;
58     }
59     
60     /**
61      * @param args
62      */
63     public static void main(String[] args) {
64         
65         Node g = new Node(null,null,7);
66         Node f = new Node(null,null,6);
67         Node e = new Node(null,null,5);
68         Node d = new Node(null,null,4);
69         Node c = new Node(f,g,3);
70         Node b = new Node(d,e,2);
71         Node a = new Node(b,c,1); 
72         
73         Node test=null;
74         test = getCommonRoot(a,b,f);
75         if(null!=test){
76             System.out.println(test.data);
77         }
78     }
79 
80 }
原文地址:https://www.cnblogs.com/chlde/p/2741380.html