1 public class Node
 2     {
 3         public int CurNode;
 4         public int FatherNode;
 5         public int Layer;
 6     }
 7 
 8     public class Solution
 9     {
10         public List<Node> L = new List<Node>();
11         public void FrontTraversal(TreeNode root, int layer = 0)
12         {
13             if (root != null)
14             {
15                 if (!L.Any())
16                 {
17                     L.Add(new Node() { CurNode = root.val, FatherNode = 0, Layer = layer });
18                 }
19                 if (root.left != null)
20                 {
21                     L.Add(new Node() { CurNode = root.left.val, FatherNode = root.val, Layer = layer + 1 });
22                     FrontTraversal(root.left, layer + 1);
23                 }
24                 if (root.right != null)
25                 {
26                     L.Add(new Node() { CurNode = root.right.val, FatherNode = root.val, Layer = layer + 1 });
27                     FrontTraversal(root.right, layer + 1);
28                 }
29             }
30 
31         }
32 
33         public bool IsCousins(TreeNode root, int x, int y)
34         {
35             FrontTraversal(root);
36             var nodeX = L.Find(c => c.CurNode == x);
37             var nodeY = L.Find(c => c.CurNode == y);
38             if (nodeX != null && nodeY != null
39                 && nodeX.FatherNode != nodeY.FatherNode
40                 && nodeX.Layer == nodeY.Layer)
41             {
42                 return true;
43             }
44             return false;
45         }
46     }

 

posted on 2019-02-17 13:43  Sempron2800+  阅读(120)  评论(0编辑  收藏  举报