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

    求一个二叉树的所有路径

    代码:

    /**
    * 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 RootPath(vector<string>& resultVec, TreeNode *root, string s)
        {
            if (root->left == NULL && root->right == NULL)
            {
                resultVec.push_back(s);
                return;
            }
            if (root->left)
            {
                RootPath(resultVec, root->left, s + "->" + to_string(root->left->val));
            }
            if (root->right)
            {
                RootPath(resultVec, root->right, s + "->" + to_string(root->right->val));
            }
        }
    
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> result;
            if (root == NULL) return result;
            RootPath(result, root, to_string(root->val));
            return result;
        }
    };
  • 相关阅读:
    函数
    关联子查询
    子查询
    视图(VIEW)
    顺时针打印矩阵
    二叉树的镜像
    树的子结构
    将两个有序链表合并
    反转链表
    输出链表中倒数第k个结点
  • 原文地址:https://www.cnblogs.com/zhangbaochong/p/5229125.html
Copyright © 2011-2022 走看看