`
javatome
  • 浏览: 824585 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

C# 二叉树GetEnumerator()方法实现非递归前序遍历

 
阅读更多

using System;
using System.Collections.Generic;
using System.Collections;

/// <summary>

/// Abstract node

/// </summary>

/// <typeparam name="T"></typeparam>

abstract class TreeNode<T> where T : TreeNode<T>

{

public T LeftNode { get; set; }

public T RightNode { get; set; }

}

/// <summary>

/// Tree class

/// </summary>

/// <typeparam name="T"></typeparam>

class Tree<T> where T : TreeNode<T>

{

/// <summary>

/// Root node

/// </summary>

public T RootNode { get; set; }

public IEnumerator GetEnumerator()

{

//Reserve nodes which have right node.

Stack<T> stack = new Stack<T>();

//Current node instance

T currentNode = RootNode;

//While current node was set as the lat node's right node, exit the cycle

while (currentNode != null)

{

//Output current node

yield return currentNode;

//If current node has right node, add it to stack

if (currentNode.RightNode != null)

{

stack.Push(currentNode);

}

//If current node has left node, set rge current node as the left node

if (currentNode.LeftNode != null)

{

currentNode = currentNode.LeftNode;

}

else

{

//If current node doesn't has left node, go to stack to get the first right node, and go on the cycle

if (stack.Count != 0)

{

currentNode = (T)stack.Pop().RightNode;

}

else

{

break;

}

}

}

}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics