zoukankan      html  css  js  c++  java
  • <LeetCode OJ> 257. Binary Tree Paths

    257. Binary Tree Paths

    Total Accepted: 29282 Total Submissions: 113527 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 getDfsPaths(vector<string>& result, TreeNode* node, string strpath) {
            if(!node->left && !node->right){//叶子
                result.push_back(strpath);
                return ;
            }
            if(node->left)
                getDfsPaths(result, node->left, strpath+"->"+to_string(node->left->val));
            if(node->right)
                getDfsPaths(result, node->right, strpath+"->"+to_string(node->right->val));
        }
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> ret;
            if(!root) 
                return ret;
            
            getDfsPaths(ret, root, to_string(root->val));
            return ret;
        }
    };


    小结:

    1。深度搜索应该立马条件反射,採用前序式遍历(假设用递归的话)

    2,深度优先搜索应该立马联想到栈来实现迭代

    3,递归具有保存变量信息的功能,有时候值得利用



    联动第二十二题

    【1】 22. Generate Parentheses。http://blog.csdn.net/ebowtang/article/details/50557414


    注:本博文为EbowTang原创,兴许可能继续更新本文。假设转载,请务必复制本条信息!

    原文地址:http://blog.csdn.net/ebowtang/article/details/50493936

    原作者博客:http://blog.csdn.net/ebowtang


  • 相关阅读:
    Codeforces Beta Round #69 (Div. 2 Only)
    Codeforces Beta Round #67 (Div. 2)
    Codeforces Beta Round #65 (Div. 2)
    UmBasketella
    Codeforces Beta Round #63 (Div. 2)
    [agc004d]Teleporter
    [arc076f]Exhausted?
    NOIp模拟赛二十八
    CDQ分治笔记
    (noip模拟二十一)【BZOJ2500】幸福的道路-树形DP+单调队列
  • 原文地址:https://www.cnblogs.com/yfceshi/p/7238196.html
Copyright © 2011-2022 走看看