public static bool IsSubTree(BinaryTreeNode<int> smallerTreeRoot, BinaryTreeNode<int> largerTreeRoot) { if (smallerTreeRoot == null) return true; else if (largerTreeRoot == null) return false; if (AreIdentical(smallerTreeRoot, largerTreeRoot)) return true; return IsSubTree(smallerTreeRoot, largerTreeRoot.Left) || IsSubTree(smallerTreeRoot, largerTreeRoot.Right); }
private static BinaryTreeNode<int> BruteForce(BinaryTreeNode<int> root, int a, int b) { BinaryTreeNode<int> n1 = BinarySearchTree.Find(root, a); BinaryTreeNode<int> n2 = BinarySearchTree.Find(root, b); int d1 = ComputeLCA.Depth(n1); int d2 = ComputeLCA.Depth(n2); while (d1 > d2) { n1 = n1.Parent; d1--; } while (d2 > d1) { n2 = n2.Parent; d2--; } while (!object.Equals(n1, n2)) { n1 = n1.Parent; n2 = n2.Parent; } return n1; }
public static BinaryTreeNode<int> FindLowestCommonAncestorInBST(BinaryTreeNode<int> root, BinaryTreeNode<int> node1, BinaryTreeNode<int> node2) { if (root == null || node1 == null || node2 == null) return null; if (root.Value > Max(node1.Value, node2.Value)) return FindLowestCommonAncestorInBST(root.Left, node1, node2); if (root.Value < Min(node1.Value, node2.Value)) return FindLowestCommonAncestorInBST(root.Right, node1, node2); return root; }
public void testNotInTree() { BinaryTreeNode<Int32> root = new BinaryTreeNode<Int32>(2); root.insert(5); root.insert(1); root.insert(16); bool exceptionCaught_v1 = false; bool exceptionCaught_v2 = false; bool exceptionCaught_v3 = false; #pragma warning disable 168 try { Assert.AreEqual(eu.sig.training.ch03.binarytree.v1.BinaryTreeSearch.calculateDepth(root, 17), 0); } catch (TreeException e) { exceptionCaught_v1 = true; } try { Assert.AreEqual(eu.sig.training.ch03.binarytree.v2.BinaryTreeSearch .calculateDepth(root, 17), 0); } catch (TreeException e) { exceptionCaught_v2 = true; } try { Assert.AreEqual(eu.sig.training.ch03.binarytree.v3.BinaryTreeSearch .calculateDepth(root, 17), 0); } catch (TreeException e) { exceptionCaught_v3 = true; } Assert.IsTrue(exceptionCaught_v1); Assert.IsTrue(exceptionCaught_v2); Assert.IsTrue(exceptionCaught_v3); #pragma warning restore 168 }
public void ShouldCorrectlyCreateRootNode() { var root = new BinaryTreeNode<int>(null); Assert.AreEqual(null, root.Parent); Assert.IsTrue(root.IsRoot); }
private BinaryTreeNode<Script> UnknowContact() { var root = new BinaryTreeNode<Script>(new Script { Question = "Could you please tell me the name of the person who is responsible for the cleaning of your premises?", Actions = new Collection<ScriptAction> { new UpdateContactName() }, }); root.Right = KnownContact(); root.Left = new BinaryTreeNode<Script>(new Script { Question = "We would like to send the relevant person some information on our services that they could find useful in the future. I do not " + "need to speak to the person. Could you just tell me their name", Actions = new Collection<ScriptAction> { new UpdateContactName() } }); root.Left.Left = End(false); root.Left.Right = End(true); return root; }
public static void findSumExDepth(BinaryTreeNode root, double threshold, int level = 0, System.Collections.Generic.List<BinaryTreeNode> list = null) { if (list == null) { list = new System.Collections.Generic.List<BinaryTreeNode>(); list.Add(root); if (root.Data == threshold) { printPath(list); } } else { list.Add(root); double tmp = threshold; for (int i = level; i >= 0; i--) { tmp -= list[i].Data; if (tmp == 0) { printPath(list, i); } } } if (root.LeftNode != null) { findSumExDepth(root.LeftNode, threshold, level + 1, clone(list)); } if (root.RightNode != null) { findSumExDepth(root.RightNode, threshold, level + 1, clone(list)); } }
public void Must_construct_root_node() { var systemUnderTest = new BinaryTreeNode(); Assert.That(systemUnderTest.Ancestor, Is.Null); Assert.That(systemUnderTest.IsRoot, Is.True); }
/// <summary> /// Initializes the BinaryTree with an array of integers. NOTE: All duplicated integers will be removed during the initialization and the tree will contain Nodes with unique values. /// </summary> /// <param name="integers">An array of integers.</param> public BinaryTree(int[] integers) { this.nodeValues = integers.Distinct().ToArray(); this.rootNode = this.buildNodeConnections(this.nodeValues); this.distinguishedNode = this.rootNode; }
public void Must_have_no_descendants() { var systemUnderTest = new BinaryTreeNode(); Assert.That(systemUnderTest.LeftDescendant, Is.Null); Assert.That(systemUnderTest.RightDescendant, Is.Null); }
public static BinaryTreeNode<int> FindNode(BinaryTreeNode<int> node, int searchValue) { if (node != null) { if (node.Value == searchValue) { CalcStack.Push(node.InitialValue.ToString()); return node; } else { var right = FindNode(node.Right, searchValue); if (right != null) { CalcStack.Push("*"); CalcStack.Push(node.InitialValue.ToString()); return right; } else { var left = FindNode(node.Left, searchValue); if (left != null) { CalcStack.Push("+"); CalcStack.Push(node.InitialValue.ToString()); return left; } } } } return null; }
public static BinaryTreeNode inorderSucc(BinaryTreeNode orignal) { if (orignal.ParentNode == null && orignal.RightNode != null) { BinaryTreeNode btn = orignal.RightNode; while (btn != null) { if (btn.LeftNode != null) { return btn.LeftNode; } btn = btn.RightNode; } } else { BinaryTreeNode btn = orignal; while (btn.ParentNode != null) { if (btn.ParentNode.LeftNode == btn) { return btn.ParentNode; } btn = btn.ParentNode; } return btn; } return null; }
// tag::calculateDepth[] public static int CalculateDepth(BinaryTreeNode<int> t, int n) { int depth = 0; if (t.Value == n) { return depth; } else { if (n < t.Value) { BinaryTreeNode<int> left = t.Left; if (left == null) { throw new TreeException("Value not found in tree!"); } else { return 1 + CalculateDepth(left, n); } } else { BinaryTreeNode<int> right = t.Right; if (right == null) { throw new TreeException("Value not found in tree!"); } else { return 1 + CalculateDepth(right, n); } } } }
////Algo // 5 // 3 7 // 1 4 6 8 int VisitNode(BinaryTreeNode<int> treeNode) { int leftVal = 0, rightVal = 0; if(treeNode.Left == null) { leftVal = -1; } else { leftVal = VisitNode(treeNode.Left); } if(treeNode.Right == null) { rightVal = -1; } else { rightVal = VisitNode(treeNode.Right); } if(Math.Abs(leftVal - rightVal) > 1) { Console.WriteLine("Tree is not balanced"); } return (leftVal > rightVal ? leftVal : rightVal) + 1; }
public void ShouldNotHaveChildNodesInitialy() { var root = new BinaryTreeNode<int>(null); Assert.IsFalse(root.HasLeftChild); Assert.IsFalse(root.HasRightChild); }
public void SatisfiesBSTTest() { Func<BinaryTreeNode<int>, bool>[] functions = new Func<BinaryTreeNode<int>, bool>[] { SatisfiesBST.BruteForce, SatisfiesBST.Recursive, SatisfiesBST.InOrderTraversal, SatisfiesBST.Queue }; for (int i = 0; i < 10; i++) { int[] data = ArrayUtilities.CreateRandomArray(10, 0, 20); BinaryTreeNode<int> root = new BinaryTreeNode<int>(data[0]); for(int j = 1; j < data.Length; j++) { BinarySearchTree.Insert(root, data[j]); Tests.TestFunctions(root, functions); } root = new BinaryTreeNode<int>(data[0]); for (int j = 1; j < data.Length; j++) { BinaryTreeUtilities.AddRandomNode(root, data[j]); Tests.TestFunctions(root, functions); } } }
public void NewNodeHasParent() { BinaryTreeNode<int> node = new BinaryTreeNode<int>(1); BinaryTreeNode<int> node2 = new BinaryTreeNode<int>(2); node.Left = node2; Assert.AreEqual(node2.Parent, node); }
public void CanGetParent() { BinaryTreeNode<int> left = new BinaryTreeNode<int>(2); BinaryTreeNode<int> right = new BinaryTreeNode<int>(3); BinaryTreeNode<int> node = new BinaryTreeNode<int>(1, left, right); Assert.AreEqual(node.Left.Parent, node); }
public static System.Collections.Generic.Dictionary<System.Int16, System.Collections.Generic.List<BinaryTreeNode>> getLevelLinkedList(BinaryTreeNode head) { System.Collections.Generic.Dictionary<System.Int16, System.Collections.Generic.List<BinaryTreeNode>> result = new System.Collections.Generic.Dictionary<System.Int16, System.Collections.Generic.List<BinaryTreeNode>>(); short level = 0; System.Collections.Generic.List<BinaryTreeNode> list = new System.Collections.Generic.List<BinaryTreeNode>(); list.Add(head); result.Add(level, list); while (true) { System.Collections.Generic.List<BinaryTreeNode> list_loop = result[level]; list = new System.Collections.Generic.List<BinaryTreeNode>(); result.Add(++level, list); foreach (BinaryTreeNode btn in list_loop) { if (btn.LeftNode != null) { list.Add(btn.LeftNode); } if (btn.RightNode != null) { list.Add(btn.RightNode); } } if (list.Count == 0) { break; } } return result; }
public static void findSum(BinaryTreeNode root, double threshold, double count = 0, System.Collections.Generic.List<BinaryTreeNode> list = null) { if (list == null) { list = new System.Collections.Generic.List<BinaryTreeNode>(); } double Data = root.Data; count += Data; list.Add(root); if (count == threshold) { printPath(list); } if (root.LeftNode != null) { findSum(root.LeftNode, threshold, count, clone(list)); findSum(root.LeftNode, threshold); } if (root.RightNode != null) { findSum(root.RightNode, threshold, count, clone(list)); findSum(root.RightNode, threshold); } }
public void CanGetChildren() { BinaryTreeNode<int> left = new BinaryTreeNode<int>(2); BinaryTreeNode<int> right = new BinaryTreeNode<int>(3); BinaryTreeNode<int> node = new BinaryTreeNode<int>(1, left, right); BinaryTreeNode<int>[] expected = new BinaryTreeNode<int>[] { left, right }; CollectionAssert.AreEqual(node.Children, expected); }
private static string Print(BinaryTreeNode t) { if (t == null) return "null"; string result = t.data.ToString(); result += "\n|\\\n" + Print(t.left) + " " + Print(t.right) + '\n'; return result; }
public void NewNodeWithChildrenHasChildren() { BinaryTreeNode<int> left = new BinaryTreeNode<int>(2); BinaryTreeNode<int> right = new BinaryTreeNode<int>(3); BinaryTreeNode<int> node = new BinaryTreeNode<int>(1, left, right); Assert.AreEqual(node.Left.Value, 2); Assert.AreEqual(node.Right.Value, 3); }
// tag::calculateDepth[] public static int calculateDepth(BinaryTreeNode<int> t, int n) { int depth = 0; if (t.getValue() == n) return depth; else return traverseByValue(t, n); }
public void BinaryTreeNodeConstructorTest() { BinaryTreeNode<int> node = new BinaryTreeNode<int>(10); Assert.AreEqual(10, node.Value); Assert.IsNull(node.Left); Assert.IsNull(node.Right); }
public void ShouldCreateBinarySearchTreeWithGivenRoot() { var rootNode = new BinaryTreeNode<int>(null); var binarySearchTree = new BinarySearchTree<int>(rootNode); Assert.AreEqual(rootNode, binarySearchTree.Root); }
private static int TraverseByValue(BinaryTreeNode<int> t, int n) { BinaryTreeNode<int> childNode = GetChildNode(t, n); if (childNode == null) { throw new TreeException("Value not found in tree!"); } else { return 1 + CalculateDepth(childNode, n); } }
// tag::calculateDepth[] public static int CalculateDepth(BinaryTreeNode<int> t, int n) { int depth = 0; if (t.Value == n) { return depth; } else { return TraverseByValue(t, n); } }
public void ShouldCreateBinarySearchTreeWithGivenRootAndUpdateTheCounter() { var rootNode = new BinaryTreeNode<int>(null); var binarySearchTree = new BinarySearchTree<int>(rootNode); Assert.AreEqual(1, binarySearchTree.Count); }
private static BinaryTreeNode<int> GetChildNode( BinaryTreeNode<int> t, int n) { if (n < t.Value) { return t.Left; } else { return t.Right; } }
public BinaryTreeNode(char data, BinaryTreeNode left) : this(data, left, null) { }
public int CompareTo(BinaryTreeNode <T> other) { return(this.value.CompareTo(other.value)); }
public BinaryTreeNode(int value) { this.value = value; this.left = null; this.right = null; }
public BinaryTreeNode insertRight(int rightValue) { this.right = new BinaryTreeNode(rightValue); return(this.right); }
public BinaryTreeNode(int n) { this.n = n; left = null; right = null; }
public static System.Collections.Generic.Dictionary <System.Int16, System.Collections.Generic.List <BinaryTreeNode> > getLevelLinkedList(BinaryTreeNode head) { System.Collections.Generic.Dictionary <System.Int16, System.Collections.Generic.List <BinaryTreeNode> > result = new System.Collections.Generic.Dictionary <System.Int16, System.Collections.Generic.List <BinaryTreeNode> >(); short level = 0; System.Collections.Generic.List <BinaryTreeNode> list = new System.Collections.Generic.List <BinaryTreeNode>(); list.Add(head); result.Add(level, list); while (true) { System.Collections.Generic.List <BinaryTreeNode> list_loop = result[level]; list = new System.Collections.Generic.List <BinaryTreeNode>(); result.Add(++level, list); foreach (BinaryTreeNode btn in list_loop) { if (btn.LeftNode != null) { list.Add(btn.LeftNode); } if (btn.RightNode != null) { list.Add(btn.RightNode); } } if (list.Count == 0) { break; } } return(result); }
public static string Print(BinaryTreeNode <int> root) { if (root == null) { throw new ArgumentNullException(nameof(root), "The root of binary tree can't be null"); } // 设立两个堆栈,其中一个在消耗元素的同时,往另一个中添加元素 // 一个堆栈消耗完毕,开始消耗另一个堆栈,同时如果有新元素需要添加,就添加到之前已经消耗完毕的堆栈中,直到另一个堆栈消耗完毕,再调转回来 Stack <BinaryTreeNode <int> > stack1 = new Stack <BinaryTreeNode <int> >(); Stack <BinaryTreeNode <int> > stack2 = new Stack <BinaryTreeNode <int> >(); StringBuilder sb = new StringBuilder(); bool leftToRight = true; stack1.Push(root); // 当两个堆栈全部清空的时候,循环才能结束 while (stack1.Count != 0 || stack2.Count != 0) { if (leftToRight) { var currentNode = stack1.Pop(); sb.Append(currentNode.Value).Append(","); // 当前层从左到右遍历时,要考虑到下一层是从右往左遍历的,所以要先将左子节点压入堆栈,再压入右子节点 if (currentNode.Left != null) { stack2.Push(currentNode.Left); } if (currentNode.Right != null) { stack2.Push(currentNode.Right); } // 当前堆栈清空以后,说明当前层级遍历结束,修改标志,改变遍历方向 // 如果是实际输出到显示屏上,可以在此加入换行符号 if (stack1.Count == 0) { leftToRight = false; } } else { var currentNode = stack2.Pop(); sb.Append(currentNode.Value).Append(","); if (currentNode.Right != null) { stack1.Push(currentNode.Right); } if (currentNode.Left != null) { stack1.Push(currentNode.Left); } if (stack2.Count == 0) { leftToRight = true; } } } return(sb.ToString(0, sb.Length - 1));// 去掉最后一个逗号 }
private static bool BruteForce(BinaryTreeNode <int> root) { return(IsHeightBalanced.BalancedHeightBruteForce(root)); }
private static void Validate(bool expected, BinaryTreeNode <int> root) { var result = Question_4_5.IsBST(root); Assert.AreEqual(expected, result); }
public void MaxDiffBetweenNodeAndAncestor(BinaryTreeNode root) { }
public BinaryTreeNode(T data, BinaryTreeNode <T> leftNode = null, BinaryTreeNode <T> rightNode = null) { Data = data; LeftNode = leftNode; RightNode = rightNode; }
private static bool Recursive(BinaryTreeNode <int> root) { return(IsHeightBalanced.BalancedHeightRecursive(root) != null); }
/// <summary> /// 二叉树节点 /// </summary> /// <param name="value">节点中的值</param> /// <param name="parent">节点的父节点</param> public BinaryTreeNode(T value, BinaryTreeNode <T> parent) { this.Value = value; this.Parent = parent; }
private void RemoveNode(BinaryTreeNode <T> toRemove, bool isLeftChild) { throw new NotImplementedException(); }
private bool RecursiveRemoveFromTree(BinaryTreeNode <T> node, T value) { throw new NotImplementedException(); }
public BinaryTree(T root) { Root = new BinaryTreeNode <T>(root); }
public virtual void Add(K key, V value) { BinaryTreeNode newNode = new BinaryTreeNode(key, value); InsertNode(newNode); }
public bool isBalanced(BinaryTreeNode treeRoot) { bool balanced = true; // Start a stack Stack <NodeDepthPair> treeStack = new Stack <NodeDepthPair>(); NodeDepthPair rootNodePair = new NodeDepthPair(treeRoot, 0); // Push in the root treeStack.Push(rootNodePair); // Declare depth holder List <int> numDepths = new List <int> (); while (treeStack.Count > 0) { NodeDepthPair curNodePair = treeStack.Pop(); Console.WriteLine("Looking at node {0}", curNodePair.node.value); // Check if this is a leaf node if (curNodePair.node.left == null && curNodePair.node.right == null) { Console.WriteLine("\tIs leaf Node at depth {0}", curNodePair.depth); // Depth is currently not represented if (!numDepths.Contains(curNodePair.depth)) { numDepths.Add(curNodePair.depth); // Conidtions for having depths that have diff greater than 1 // Number of depths is greater than 2, then we probably if (numDepths.Count > 2) { return(false); } // There are 2 depths and their diff is greater than 1 if (numDepths.Count == 2) { if (Math.Abs(numDepths[0] - numDepths[1]) > 1) { return(false); } } } } // This node has children else { // If there is a left node if (curNodePair.node.left != null) { // put that on the stack treeStack.Push(new NodeDepthPair(curNodePair.node.left, curNodePair.depth + 1)); } // If there is a left node if (curNodePair.node.right != null) { // put that on the stack treeStack.Push(new NodeDepthPair(curNodePair.node.right, curNodePair.depth + 1)); } } } return(balanced); }
private static void ProcessNode(BinaryTreeNode root) { Console.Write(root.Data + " "); }
public BinarySearchTree() { this.root = null; }
static void Main(string[] args) { BinaryTreeNode root = new BinaryTreeNode(1); root.Left = new BinaryTreeNode(2); root.Right = new BinaryTreeNode(3); root.Left.Left = new BinaryTreeNode(4); root.Left.Right = new BinaryTreeNode(10); root.Left.Left.Left = new BinaryTreeNode(7); root.Left.Left.Right = new BinaryTreeNode(5); root.Right.Left = new BinaryTreeNode(7); root.Right.Right = new BinaryTreeNode(10); root.Right.Left.Left = new BinaryTreeNode(8); root.Right.Left.Right = new BinaryTreeNode(9); root.Right.Right.Right = new BinaryTreeNode(11); //BinaryTreeNode root = new BinaryTreeNode(50); //var node2 = new BinaryTreeNode(2); //var node3 = new BinaryTreeNode(3); //var node4 = new BinaryTreeNode(4); //var node5 = new BinaryTreeNode(5); //var node6 = new BinaryTreeNode(6); //var node7 = new BinaryTreeNode(7); //root.Left = node2; //root.Right = node3; //node2.Left = node4; //node2.Right = node5; //node3.Left = node6; //node3.Right = node7; //var watch = System.Diagnostics.Stopwatch.StartNew(); //Console.WriteLine(GetMaximumRecursive(root)); //watch.Stop(); //Console.Write(" Time: " + watch.ElapsedMilliseconds + " ms"); //watch.Restart(); //Console.WriteLine(GetMaximumIterative(root)); //watch.Stop(); //Console.Write(" Time: " + watch.ElapsedMilliseconds + " ms"); var watch = System.Diagnostics.Stopwatch.StartNew(); Console.Write("Recursive: "); InOrderRecursive(root); watch.Stop(); Console.Write(" Time: " + watch.ElapsedMilliseconds + " ms"); Console.WriteLine(); watch.Restart(); Console.Write("Iterative: "); InOrderIterative(root); watch.Stop(); Console.Write(" Time: " + watch.ElapsedMilliseconds + " ms"); Console.ReadLine(); }
public void SetChildNode(ChildNode selectedNode, BinaryTreeNode node) { childNode[(int)selectedNode] = node; }
public NodeDepthPair(BinaryTreeNode node, int depth) { this.node = node; this.depth = depth; }
public int CompareTo(BinaryTreeNode otherNode) { return(value.CompareTo(otherNode.value)); }
public BinaryTreeNode insertLeft(int leftValue) { this.left = new BinaryTreeNode(leftValue); return(this.left); }
public BinaryTreeNode(char data, BinaryTreeNode left, BinaryTreeNode right) { this.data = data; this.left = left; this.right = right; }
public void Insert(int n) { Root = Insert(Root, n); }
public BinaryTreeNode(T value) : this(value, null, null) { parent = null; }
public BinaryTree() { Root = null; }
//LCA of binary tree private static BinaryTreeNode LCA_BT(BinaryTreeNode Root, BinaryTreeNode Node1, BinaryTreeNode Node2) { if (Root == null || Node1 == null || Node2 == null) { return(null); } if (Root == Node1 || Root == Node2) { return(Root); } BinaryTreeNode leftLca = LCA_BT(Root.left, Node1, Node2); BinaryTreeNode rightLca = LCA_BT(Root.right, Node1, Node2); if (leftLca != null && rightLca != null) { return(Root); } if (leftLca != null) { return(leftLca); } return(rightLca); }