清凉世界

喜欢喜欢我的...

  博客园 :: 首页 :: 联系 :: 订阅 订阅 :: 管理
  6 Posts :: 2 Stories :: 11 Comments :: 0 Trackbacks

2008年5月17日 #

        工作一段时间了,有点想跳曹,一部分为了钱,一部分为了更好的发展,在招聘专区投了份微创的简历,本以为是没戏了,一个星期后给我打了个电话,当时还在办公室,只能跑出去了,结果电话里给我出了些题目,全是关于树的.答对了写,有些也答不上了.
        记的有题是说不用递归遍历2叉树.今天有空就写写.
        先贴原码.
using System;
using System.Collections.Generic;
using System.Text;

namespace TREE
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            TreeControl treecontrol 
= new TreeControl();
            TreeNode mytree 
=treecontrol.CreateTree();
            printTree(mytree);
            Console.WriteLine(
"haha");
            whileprinttree(mytree);
            Console.WriteLine(
"heihei");
         
        }



        
/// <summary>
        
/// 递归法
        
/// </summary>
        
/// <param name="mytree"></param>

        public static void printTree(TreeNode mytree)
        
{
            
if (mytree != null)
            
{
                Console.WriteLine(mytree.NodeValue);
                printTree(mytree.RightChild);
                printTree(mytree.LeftChild);
            }

        }


        
/// <summary>
        
/// 非递归法
        
/// </summary>
        
/// <param name="mytree"></param>

        public static void whileprinttree(TreeNode mytree)
        
{
            Stack
<TreeNode> mystack = new Stack<TreeNode>();
            mystack.Push(mytree);
            
while (mystack.Count != 0)
            

                TreeNode node 
= mystack.Pop();
                Console.WriteLine(node.NodeValue.ToString());
                
if (node.RightChild != null)
                
{
                    mystack.Push(node.RightChild);
                }

                
if (node.LeftChild != null)
                
{
                    mystack.Push(node.LeftChild);
                }

            }

        }

        
    }


    
}



   递归的方法就不用多说了,说下不用递归的方法.
先构造一棵树,然后创建一个堆栈.
如图1

然后访问跟节点1,放入堆栈,接着while判断堆栈是否为空,在把节点1出堆栈
出堆栈后访问两个孩子节点,并把孩子节点入栈.

接着就是把孩子节点出堆栈,在访问孩子节点2,然后把2的孩子节点入堆栈

以下步骤就不说了 给图就明白了.

最后堆栈为空退出循环.整个树就访问完了.


请大家指正.
posted @ 2008-05-17 11:29 清凉tea 阅读(39) | 评论 (0)编辑