private BinaryTreeItem FindRightParentTreeItemForIndex(int targetChildLevel, int i) { BinaryTreeItem parentItem = this; for (int level = 0; level < targetChildLevel - 1; level++) { parentItem = (level < (targetChildLevel - i - 1)) ? parentItem.Left : parentItem.Right; } return(parentItem); }
public BinaryTree AddLevel(params int[] items) { if (++_maxLevel != items.Length - 1) { throw new ArgumentException("Expected " + (items.Length - 1) + " items in the array for level " + _maxLevel); } if (_maxLevel == 1) { Left = new BinaryTreeItem { Value = items[0], Level = _maxLevel, Index = 0 }; Right = new BinaryTreeItem { Value = items[1], Level = _maxLevel, Index = 1 }; _levels.Add(_maxLevel, new List <BinaryTreeItem> { Left, Right }); } else { _levels.Add(_maxLevel, new List <BinaryTreeItem>()); for (int i = 0; i < items.Length; i++) { var treeItem = new BinaryTreeItem { Value = items[i], Level = _maxLevel, Index = i }; _levels[_maxLevel].Add(treeItem); if (i != 0) { FindRightParentTreeItemForIndex(_maxLevel, i - 1).Right = treeItem; } if (i != (items.Length - 1)) { FindRightParentTreeItemForIndex(_maxLevel, i).Left = treeItem; } } } return(this); }