zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    HSSFworkbook,XSSFworkbook,SXSSFworkbook区别总结
    var、let、const的区别
    寻找数组中的质数方法
    lintcode刷题笔记(二)
    CUDA11.2环境上MXNet源码和pytorch源码编译
    protobuf的使用(python)
    Hadoop集群安装-CDH5(5台服务器集群)
    Hadoop 2.6.0 HA高可用集群配置详解(一)
    Hadoop系列之(二):Hadoop集群部署
    Hadoop系列之(一):Hadoop单机部署
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10105541.html
Copyright © 2011-2022 走看看