• 257. Binary Tree Paths


    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
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    软件开发术语定义
    软件开发流程纲要及各个阶段产生的文档
    Java封装自己的Api
    Java中如何使封装自己的类,建立并使用自己的类库?
    Struts2中ActionContext和ServletActionContext
    TP-Link 无线路由器设置图文教程----怎么设置TP-Link无线路由器图解
    数据库(第一范式,第二范式,第三范式)
    ORACLE配置tnsnames.ora文件实例
    Windows下64位Apache服务器的安装
    公司内部Oracle RAC测试环境的简单使用说明.
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10105541.html
Copyright © 2020-2023  润新知