题目:
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3
解释:
返回二叉树中所有从root到leaf的路径,第一反应就是用dfs做。
python代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
result=[]
def dfs(root,s,result):
if root.left==None and root.right==None:
result.append(s)
if root.left!=None:
dfs(root.left,s+"->"+str(root.left.val),result)
if root.right!=None:
dfs(root.right,s+"->"+str(root.right.val),result)
if root:
dfs(root,str(root.val),result)
return result
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> result;
if (root)
dfs(root,to_string(root->val),result);
return result;
}
void dfs(TreeNode* root,string s,vector<string>&result)
{
if (root->left==NULL &&root->right==NULL)
result.push_back(s);
if (root->left)
dfs(root->left,s+"->"+to_string(root->left->val),result);
if(root->right)
dfs(root->right,s+"->"+to_string(root->right->val),result);
}
};
总结:
就是很经典的dfs的题目,注意dfs的时候有些判断是无意义的,去掉以后速度会有很明显的提升哦,尽量在进入dfs之前先做好条件判断,因为入栈还要花费一定的时间。