数据结构(树)

题目1:二叉树的镜像

思路:递归

        8                                8

   6      10        转换成     10     6

5    7   9    11             11   9  7    5

 

 static void SwapNode(Node node)
        {
            if (node == null)
            {
                return;
            }

            Node temp = node.Left;

            node.Left = node.Right;
            node.Right = temp;

            SwapNode(node.Left);
            SwapNode(node.Right);
        }

 题目2:从上往下打印二叉树

思路:利用队列(广度优先)

 

    static void PrintFromTopToBottom(Node node)
        {
            if (node == null)
            {
                return;
            }
            Queue<Node> queue = new Queue<Node>();
            queue.Enqueue(node);
            while (queue.Count > 0)
            {
                Node current = queue.Dequeue();
                Console.WriteLine(current.Value);
                if (current.Left != null)
                {
                    queue.Enqueue(current.Left);
                }
                if (current.Right != null)
                {
                    queue.Enqueue(current.Right);
                }
            }
        }

 

 题目3:二叉树中和为某一值的路径

题目:输入一颗二叉树和一个整数,打印出二叉树中结点值和为输入整数的所有路径。从树的根节点开始往下一直到叶结点所经过的结点形成一条路径

思路:采用前序遍历加栈。当遍历到某结点时,将该结点的值压入栈内,当遍历到叶结点的时候,计算栈中值的和,如果和等于输入整数,则打印出该路径。如果不是叶结点则继续利用递归往下遍历,然后逐一弹出栈里的值。

 

        static void FindPath(Node node, int currentSum, Stack<int> pathStack, int expecteSum)
        {
            currentSum += node.Value;//加上当前值
            pathStack.Push(node.Value);//推入栈
            bool isLeaf = node.Left == null && node.Right == null;//判断是否叶结点
            if (isLeaf && currentSum == expecteSum)
            {
                //如果是叶结点并且等于预期的值
                foreach (var item in pathStack)
                {
                    //打印
                    Console.Write(item);
                    Console.Write(",");
                }
                Console.Write(Environment.NewLine);
            }
            if (node.Left != null)
            {
                //递归
                FindPath(node.Left, currentSum, pathStack, expecteSum);
            }
            if (node.Right != null)
            {
                //递归
                FindPath(node.Right, currentSum, pathStack, expecteSum);
            }
            //出栈
            pathStack.Pop();
        }

 

 题目4:二叉树的深度

思路:采用递归 

   static int GetNodesDepth<T>(TreeNode<T> node)
        {
            int leftDepth = 0;
            int rightDepth = 0;
            if (node.Left != null)
            {
                leftDepth = GetNodesDepth(node.Left);
            }

            if (node.Right != null)
            {
                rightDepth = GetNodesDepth(node.Right);
            }

            return Math.Max(leftDepth, rightDepth) + 1;
        }

 

posted @ 2015-09-14 21:38  莱茵哈特  阅读(192)  评论(0编辑  收藏  举报