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);
        }
    };
  • 相关阅读:
    快速排序
    优先队列
    堆排序
    树、二叉树基础
    分治法
    递归算法详细分析
    算法基础
    Linux文件系统详解
    fs/ext2/inode.c相关函数注释
    块设备的读流程分析
  • 原文地址:https://www.cnblogs.com/shvier/p/4858956.html
Copyright © 2011-2022 走看看