var root = new TreeNode<int>(1); var leftChild = new TreeNode<int>(2); var rightChild = new TreeNode<int>(3); root.LeftChild = leftChild; // 1 -> 2 root.RightChild = rightChild; // 1 -> 3
插入与删除节点
1 2 3
var newNode = new TreeNode<int>(4); root.LeftChild = newNode; // 将父节点的左子节点指向新节点 newNode.LeftChild = leftChild; // 将新节点的左子节点指向曾经的左子节点
var root = new TreeNode<int>(1); root.LeftChild = new TreeNode<int>(2); root.RightChild = new TreeNode<int>(3); root.LeftChild.LeftChild = new TreeNode<int>(4); root.LeftChild.RightChild = new TreeNode<int>(5); root.RightChild.LeftChild = new TreeNode<int>(6); root.RightChild.RightChild = new TreeNode<int>(7);
之后采取层序遍历:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
IEnumerable<T> LevelOrder<T>(TreeNode<T> root) { var queue = new Queue<TreeNode<T>>(); // 初始化队列 queue.Enqueue(root); // 根节点入队 while (queue.Count != 0) { TreeNode<T> node = queue.Dequeue(); yieldreturn node.Value; // 迭代地返回节点值 if (node.LeftChild != null) queue.Enqueue(node.LeftChild); // 左子节点入队 if (node.RightChild != null) queue.Enqueue(node.RightChild); // 右子节点入队 } }