14-Line C# StringBuilder Solution -- Recursive and BFS Iterative


  • 1
    L

    1.Recursive

    public class Solution {
        IList<string> result = new List<string>();
        StringBuilder sb = new StringBuilder();
        public IList<string> BinaryTreePaths(TreeNode root) {
            if(root != null && root.left == null && root.right == null){
                result.Add(sb.Append(root.val).ToString());
                sb.Length -= root.val.ToString().Length;
            }
            else if(root != null){
                string tmp = root.val + "->";
                sb.Append(tmp);
                if(root.left != null) BinaryTreePaths(root.left);
                if(root.right != null) BinaryTreePaths(root.right);
                sb.Length -= tmp.Length;
            }
            return result;
        }
    }
    

    2.BFS Iterative

    public IList<string> BinaryTreePaths(TreeNode root) {
        Queue<TreeNode> queue = new Queue<TreeNode>();
        Queue<string> qStr = new Queue<string>();
        IList<string> result = new List<string>();
        if(root == null) return result;
        queue.Enqueue(root); qStr.Enqueue(root.val.ToString());
        while(queue.Count != 0){
            TreeNode cur = queue.Dequeue();
            string curStr = qStr.Dequeue();
            if(cur.left == null && cur.right == null) result.Add(curStr);
            if(cur.left != null){
                queue.Enqueue(cur.left);
                qStr.Enqueue(curStr + "->" + cur.left.val);
            }
            if(cur.right != null){
                queue.Enqueue(cur.right);
                qStr.Enqueue(curStr + "->" + cur.right.val);
            }
        }
        return result;
    }

Log in to reply
 

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