leetcode107

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    //二叉树层序遍历(广度优先搜索)

        private List<TreeNode> GetNext(List<TreeNode> nodes)
        {
            var list = new List<TreeNode>();

            foreach (var node in nodes)
            {
                if (node.left != null)
                {
                    list.Add(node.left);
                }
                if (node.right != null)
                {
                    list.Add(node.right);
                }
            }
            return list;
        }

        public IList<IList<int>> LevelOrderBottom(TreeNode root)
        {
            var list = new List<IList<int>>();

            if (root != null)
            {
                var rootlist = new List<TreeNode>();
                rootlist.Add(root);

                var nlist = new List<int>();
                nlist.Add(root.val);
                list.Add(nlist);

                while (rootlist.Count > 0)
                {
                    rootlist = GetNext(rootlist);

                    var xlist = new List<int>();
                    foreach (var r in rootlist)
                    {
                        xlist.Add(r.val);
                    }
                    if (xlist.Any())
                    {
                        list.Add(xlist);
                    }
                }
                list.Reverse();
            }
            return list;

        }
}

https://leetcode.com/problems/binary-tree-level-order-traversal-ii/#/description

原文地址:https://www.cnblogs.com/asenyang/p/6736445.html