给定一个二叉树,返回从根节点到叶节点的所有路径。
例如,给定以下二叉树:
1
/
2 3
5
所有根到叶路径是:
["1->2->5", "1->3"]
详见:https://leetcode.com/problems/binary-tree-paths/description/
Java实现:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> res=new ArrayList<String>(); if(root==null){ return res; } helper(root,"",res); return res; } private void helper(TreeNode root,String out,List<String> res){ out+=String.valueOf(root.val); if(root.left==null&&root.right==null){ res.add(out); } if(root.left!=null){ helper(root.left,out+"->",res); } if(root.right!=null){ helper(root.right,out+"->",res); } } }
C++实现:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; if(root) { helper(root,"",res); } return res; } void helper(TreeNode *root,string out,vector<string> &res) { out+=to_string(root->val); if(!root->left&&!root->right) { res.push_back(out); } if(root->left) { helper(root->left,out+"->",res); } if(root->right) { helper(root->right,out+"->",res); } } };
参考:https://www.cnblogs.com/grandyang/p/4738031.html