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);
        }
    };
  • 相关阅读:
    PHP array_intersect_uassoc
    PHP array_intersect_key
    PHP array_intersect_assoc
    PHP array_flip
    PHP array_filter
    PHP array_fill
    PHP array_fill_keys
    Android4.0-Fragment框架实现方式剖析
    Fragment 生命周期
    WebView
  • 原文地址:https://www.cnblogs.com/shvier/p/4858956.html
Copyright © 2011-2022 走看看