C# solution - recursive with two lists


  • 0
    A
    public class Solution {
        public IList<string> BinaryTreePaths(TreeNode root) {
            if(root == null)
                return new List<string>();
            
            var list = new List<string>();
            var stack = new List<int>();
            getPaths(root, ref stack, ref list);
            
            return list;
        }
        
        private void getPaths(TreeNode node, ref List<int> stack, ref List<string> list) {
            stack.Add(node.val);
            bool isLeaf = (node != null && node.left == null && node.right == null);
            
            if(isLeaf) {
                if(stack.Count == 1)
                    list.Add(stack.First().ToString());
                else if(stack.Count > 1)
                    list.Add(String.Join("->", stack));
            } 
            
            if(node.left != null)
                getPaths(node.left, ref stack, ref list);
            
            if(node.right != null)
                getPaths(node.right, ref stack, ref list);
            
            stack.RemoveAt(stack.Count - 1);
        }
    }

Log in to reply
 

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