zoukankan      html  css  js  c++  java
  • 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"]

    看到树相关的题目,第一反应就是递归,下面是我的代码:

    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if (root != NULL)
        {
            char buf[20];
            sprintf(buf, "%d", root->val);
            string rootPath = buf;
            if (root->left == NULL && root->right == NULL)
            {
                res.push_back(rootPath);
            }
            else
            {
                if (root->left)
                {
                    vector<string> leftPath;
                    leftPath = binaryTreePaths(root->left);
                    for (vector<string>::iterator it = leftPath.begin(); it != leftPath.end(); ++it)
                    {
                        res.push_back(rootPath + "->" + *it);
                    }
                }
                if (root->right)
                {
                    vector<string> rightPath;
                    rightPath = binaryTreePaths(root->right);
                    for (vector<string>::iterator it = rightPath.begin(); it != rightPath.end(); ++it)
                    {
                        res.push_back(rootPath + "->" + *it);
                    }
                }
            }
        }
        return res;
    }

    想要简洁一点的,可以参考https://leetcode.com/discuss/52030/c-simple-4ms-recursive-solution

  • 相关阅读:
    1-29反射
    1-28Map简介
    1-27TreeSet简介
    1-26HashSet简介
    1-25泛型
    1-24List三个子类的特点
    1-23集合概述
    Java接口
    1-22日期类型
    简易计算器的实现
  • 原文地址:https://www.cnblogs.com/gattaca/p/4750869.html
Copyright © 2011-2022 走看看