C#二叉树

public class TreeNode
    {
        private T data;
        private TreeNode leftNode;
        private TreeNode rightNode;
        public TreeNode(T nodeValue)
        {
            data = nodeValue;
            leftNode = null;
            rightNode = null;
        }
        //数据
        public T Data
        {
            get { return data; }
            set { data = value; }
        }
        //左子树
        public TreeNode LeftNode
        {
            get { return leftNode; }
            set { leftNode = value; }
        }
        //右子树
        public TreeNode RightNode
        {
            get { return rightNode; }
            set { rightNode = value; }
        }
        /// 
        /// 前序遍历:先跟节点然后左子树,右子树
        /// 
        /// 
        public void PreOrderTree(TreeNode root)
        {
            if (root != null)
            {
                Console.Write(root.Data);
                PreOrderTree(root.LeftNode);
                PreOrderTree(root.RightNode);
            }
        }
        /// 
        /// 中序遍历:左子树,根节点,右子树可以实现顺序输出
        /// 
        /// 
        public void InOrderTree(TreeNode root)
        {
            if (root != null)
            {
                InOrderTree(root.LeftNode);
                Console.Write(root.Data);
                InOrderTree(root.RightNode);
            }
        }
        /// 
        /// 深度
        /// 
        /// 
        /// 
        public int GetTreeDepth(TreeNode tree)
        {
            if (tree == null)
                return 0;
            int leftDepth = GetTreeDepth(tree.LeftNode);
            int rightDepth = GetTreeDepth(tree.RightNode);
            return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1);
        }
    }

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注