力扣0107——二叉树的层序遍历II

二叉树的层序遍历II

难度:中等

题目描述

给你二叉树的根节点 root ,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

示例1

输入: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]

示例2

输入: inorder = [-1], postorder = [-1]
输出:[-1]

题解

和 0102 题解题思路相同,不同的只不过是最后将List加入到List中的时候变为Insert即可

想法代码

public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
    {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution
{
    public static void Main(string[] args)
    {
        TreeNode root = new TreeNode(3)
        {
            left = new TreeNode(9),
            right = new TreeNode(20)
            {
                left = new TreeNode(15),
                right = new TreeNode(7)
            }
        };
        Solution solution = new Solution();
        IList<IList<int>> ans = solution.LevelOrderBottom(root);
        foreach (var a in ans)
        {
            foreach (var b in a)
            {
                Console.Write(b + " ");
            }
            Console.WriteLine();
        }
    }

    public IList<IList<int>> LevelOrderBottom(TreeNode root)
    {
        IList<IList<int>> ans = new List<IList<int>>();
        if (root == null)
        {
            return ans;
        }
        Queue<TreeNode> queue = new Queue<TreeNode>();
        queue.Enqueue(root);
        while (queue.Count > 0)
        {
            IList<int> tmp = new List<int>();
            int count = queue.Count;
            for (int i = 0; i < count; i++)
            {
                TreeNode treeNode = queue.Dequeue();
                tmp.Add(treeNode.val);
                if (treeNode.left != null)
                {
                    queue.Enqueue(treeNode.left);
                }

                if (treeNode.right != null)
                {
                    queue.Enqueue(treeNode.right);
                }
            }
            ans.Insert(0,tmp);
        }
        return ans;
    }
}

你可能感兴趣的:(算法进修,leetcode,算法,职场和发展)