leetcode257

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    Stack<TreeNode> S = new Stack<TreeNode>();

        List<List<string>> list = new List<List<string>>();

        private void postNode(TreeNode root)
        {
            if (root != null)
            {
                S.Push(root);
                if (root.left != null)
                {
                    postNode(root.left);
                }
                if (root.right != null)
                {
                    postNode(root.right);
                }
                if (root.left == null && root.right == null)
                {
                    var l = S.Reverse().ToList();
                    var n = new List<string>();
                    foreach (var d in l)
                    {
                        n.Add(d.val.ToString());
                    }
                    list.Add(n);
                }
                S.Pop();
            }
        }

        public IList<string> BinaryTreePaths(TreeNode root)
        {
            var result = new List<string>();

            postNode(root);
            foreach (var d in list)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < d.Count; i++)
                {
                    sb.Append(d[i]);
                    if (i != d.Count - 1)
                    {
                        sb.Append("->");
                    }
                }
                result.Add(sb.ToString());
            }
            return result;
        }
}

https://leetcode.com/problems/binary-tree-paths/#/description

时间: 2024-08-06 09:48:46

leetcode257的相关文章

[LeetCode257]Binary Tree Paths

题目: Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / 2 3 5 All root-to-leaf paths are: ["1->2->5", "1->3"] 求一个二叉树的所有路径 代码: /** * Definition for a binary tree node. * struct

LeetCode257 BinaryTreePaths(打印根节点到叶子节点的左右路径) Java题解

题目: Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / 2 3 5 All root-to-leaf paths are: ["1->2->5", "1->3"] 题解: 用深度优先遍历,类似二叉树的前序变遍历 代码: public class LeetCode257_BinaryTreePat

LeetCode257——Binary Tree Paths

Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / 2 3 5 All root-to-leaf paths are: ["1->2->5", "1->3"] 实现: /** * Definition for a binary tree node. * struct TreeNode { *    

leetcode--257.Binary Tree Paths

使用深度优先搜索的方法遍历每一条枝,遍历完的终止条件为左右子树都为空,这时候将这条枝的string 插入vector 中. class Solution { public: // vector 一直插入string,所以为引用类型,string不能是引用类型 void dfs(TreeNode *root, vector<string> & result, string temp) { if(root->left==NULL&&root->right==NU