zoukankan      html  css  js  c++  java
  • Binary Tree Paths

    Binary Tree Paths

    Total Accepted: 26174 Total Submissions: 104545 Difficulty: Easy

    Given a binary tree, return all root-to-leaf paths.

    For example, given the following binary tree:

       1
     /   
    2     3
     
      5
    

    All root-to-leaf paths are:

    ["1->2->5", "1->3"]
    /**
     * 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:
        void binaryTreePaths(TreeNode* root,vector<string>& paths,string path){
            if(!root) return;
            
            int path_size = path.size();
            
            string valstr = path_size ==0 ? to_string(root->val) : "->"+to_string(root->val);
             
            path.append(valstr.begin(),valstr.end());
            
            if(root->left==NULL && root->right==NULL){
                paths.push_back(path);
                return;
            }
            
            binaryTreePaths(root->left,paths,path);
            binaryTreePaths(root->right,paths,path);
            
        }
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> paths;
            string path;
            binaryTreePaths(root,paths,path);
            return paths;
        }
    };
  • 相关阅读:
    POJ1296
    BZOJ1003
    POJ1160
    中国剩余定理(转)
    组合数公式
    网络操作系统*习题
    网络操作系统*习题
    网络操作系统习题
    网络操作系统习题
    Access总结
  • 原文地址:https://www.cnblogs.com/zengzy/p/5054333.html
Copyright © 2011-2022 走看看