Пример #1
0
        private LinkedList <TreeNodeFather> BFS(TreeNode root)
        {
            LinkedList <(TreeNodeFather, TreeNode)> queue = new LinkedList <(TreeNodeFather, TreeNode)>();
            TreeNodeFather rootFather          = new TreeNodeFather(root, null, false);
            LinkedList <TreeNodeFather> result = new LinkedList <TreeNodeFather>();

            queue.AddLast((rootFather, root));

            while (queue.Count != 0)
            {
                (var nodeFather, var node) = queue.First.Value;
                queue.RemoveFirst();

                bool isLeave = true;
                if (node.left != null)
                {
                    nodeFather.left = new TreeNodeFather(node.left, nodeFather, true);
                    queue.AddLast((nodeFather.left as TreeNodeFather, node.left));
                    isLeave = false;
                }

                if (node.right != null)
                {
                    nodeFather.right = new TreeNodeFather(node.right, nodeFather, false);
                    queue.AddLast((nodeFather.right as TreeNodeFather, node.right));
                    isLeave = false;
                }

                if (isLeave)
                {
                    result.AddLast(nodeFather);
                }
            }
            return(result);
        }
Пример #2
0
 public TreeNodeFather(TreeNode node, TreeNodeFather father, bool isLeftChild)
     : base(node.val)
 {
     Father = father;
     if (father != null)
     {
         if (isLeftChild)
         {
             father.left = node;
         }
         else
         {
             father.right = node;
         }
     }
 }