zoukankan      html  css  js  c++  java
  • 【ACM从零开始】LeetCode OJ-Binary Tree Paths

    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"]
    题目大意:给出一个二叉树,输出前序遍历的信息。
    解题思路:基础题,用DFS搜索即可。
    AC代码:
    class Solution
    {
    public:
        vector<string> binaryTreePaths(TreeNode* root)
        {
            vector<string> path;
            DFS(root,path,"");
            return path;
        }
       
        void DFS(TreeNode* root,vector<string>& path,string ans)
        {
            if(!root)
                return;
            ans += to_string(root->val);
            if(root->left)
                DFS(root->left,path,ans+"->");
            if(root->right)
                DFS(root->right,path,ans+"->");
            if(!root->left && !root->right)
                path.push_back(ans);
        }
    };
  • 相关阅读:
    Girls and Boys
    Kindergarten
    codevs 2822 爱在心中
    Popular Cows
    QWQ
    2488 绿豆蛙的归宿(拓扑+dp)
    P1119 灾后重建
    Mr. Frog’s Game
    Basic Data Structure
    A strange lift
  • 原文地址:https://www.cnblogs.com/shvier/p/4858956.html
Copyright © 2011-2022 走看看