Binary Tree Paths

Source: Internet
Author: User



The problem using deep search can be done (in fact, many of the tree problems with deep search ideas can be solved), from the root node to record the path of each node, each to a leaf node to the path into the result vector can be.

/** * 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:string int2str (int src) {stringstream dst;        DST << src;    return Dst.str (); } void Exectraverl (treenode* root, vector<string> &result, string tmp) {if (root-left = = nullptr            && root, right = = nullptr) {tmp + = ";            TMP + = Int2str (root, Val);            Result.push_back (TMP);        Return            } if (root-left! = nullptr) {string TMP1 = tmp;            TMP1 + = ";            TMP1 + = Int2str (root, Val);        Exectraverl (Root-left, result, TMP1);            } if (root-right! = nullptr) {string TMP2 = tmp;            TMP2 + = ";            TMP2 + = Int2str (root, Val); ExectraverL (Root-right, result, TMP2);        }} vector<string> binarytreepaths (treenode* root) {string tmp;                vector<string> result;                if (root = = nullptr) return result;            if (root, left = = nullptr && root, right = = nullptr) {tmp + = Int2str (root, Val);            Result.push_back (TMP);        return result;            } if (root-left! = nullptr) {string tmp1;            TMP1 + = Int2str (root, Val);        Exectraverl (Root-left, result, TMP1);            } if (root-right! = nullptr) {string tmp2;            TMP2 + = Int2str (root, Val);        Exectraverl (Root-right, result, TMP2);    } return result; }};


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Binary Tree Paths

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.