C# recursive solution


  • 0
    A
    public class Solution {
        IList<IList<int>> res = new List<IList<int>>();
        public IList<IList<int>> LevelOrder(TreeNode root) {
            if(root==null)
                return res;
            IList<TreeNode> rootNodeList = new List<TreeNode>();
            rootNodeList.Add(root);
            GetAllChildrenAndAdd(rootNodeList);
            return res;
        }
        
        private  void GetAllChildrenAndAdd(IList<TreeNode> nodes)
        {
            IList<int> allChildrenVal = new List<int>();
            IList<TreeNode> allChildrenNodes = new List<TreeNode>();
            foreach (TreeNode node in nodes)
            {
                allChildrenVal.Add(node.val);
                if(node.left!=null)
                    allChildrenNodes.Add(node.left);
                if(node.right!=null)
                    allChildrenNodes.Add(node.right);
                
            }
            if(allChildrenVal.Count>0)
                res.Add(allChildrenVal);
    
            if(allChildrenNodes.Count>0)
                GetAllChildrenAndAdd(allChildrenNodes);
        }
        
        
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.