码迷,mamicode.com
首页 > 其他好文 > 详细

257. Binary Tree Paths

时间:2018-12-12 00:08:53      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:pre   tree   tac   help   roo   lse   pop   ring   vat   

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

 

Approach #1: C++. [recursive]

/**
 * 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> ans;
        if (root == NULL) return ans;
        helper(root, ans, "");
        return ans;
    }
    
private:
    void helper(TreeNode* root, vector<string>& ans, string str) {
        if (root == NULL) return;

        if (str == "") str += to_string(root->val);
        else str += "->" + to_string(root->val);
        
        if (root->left == NULL && root->right == NULL) 
            ans.push_back(str);
        
        helper(root->left, ans, str);
        helper(root->right, ans, str);
    }
};

  

Approach #2: Java. [dfs + stack]

/**
 * 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> ans = new ArrayList<>();
        
        if (root == null) return ans;
        
        Stack<TreeNode> sNode = new Stack<>();
        Stack<String> sStr = new Stack<>();
        sNode.push(root);
        sStr.push("");
        
        while (!sNode.isEmpty()) {
            TreeNode curNode = sNode.pop();
            String curStr = sStr.pop();
            if (curNode.left == null && curNode.right == null) ans.add(curStr+curNode.val);
            if (curNode.left != null) {
                sNode.push(curNode.left);
                sStr.push(curStr + curNode.val + "->");
            }
            if (curNode.right != null) {
                sNode.push(curNode.right);
                sStr.push(curStr + curNode.val + "->");
            }
        }
        
        return ans;
    }
}

  

Appraoch #3: Python. [bfs + queue]

# 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 []
        res, queue = [], collections.deque([(root, "")])
        while queue:
            node, ls = queue.popleft()
            if not node.left and not node.right:
                res.append(ls + str(node.val))
            if node.left:
                queue.append((node.left, ls + str(node.val) + "->"))
            if node.right:
                queue.append((node.right, ls + str(node.val) + "->"))
        return res

  

 

257. Binary Tree Paths

标签:pre   tree   tac   help   roo   lse   pop   ring   vat   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/10105541.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!