题解 | #求二叉树的层序遍历#

求二叉树的层序遍历

http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3

using System;
using System.Collections.Generic;

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

	public TreeNode (int x)
	{
		val = x;
	}
}
*/

class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型二维数组
     */
    public List<List<int>> levelOrder (TreeNode root) {
        // write code here
        List<List<int>> ans=new List<List<int>>();
        Sub(root,0,ref ans);
        return ans;
    }
    
    public void Sub(TreeNode root,int layer,ref List<List<int>> ans)
    {
        if(root==null)
            return;
        if(ans.Count<layer+1)
        {
            List<int> newLayer=new List<int>();
            ans.Add(newLayer);
        }
        ans[layer].Add(root.val);
        Sub(root.left,layer+1,ref ans);
        Sub(root.right,layer+1,ref ans);
        return;
    }
    
    
    
}
C#  版的递归操作。没啥多说的
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务