LeetCode-257. Binary Tree Paths

問題:
https://leetcode.com/problems/binary-tree-paths/?tab=Description
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”]
分析:
樹的深度優先遍歷。使用遞歸的方法來進行求解的,從根節點開始,若左子樹不爲空,則遍歷左子樹,若左子樹的左孩子不爲空,則遍歷左孩子,否則遍歷右孩子…..直到遍歷完最後一個葉子節點爲止。
參考C++代碼:

/**
 * 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:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;  
        if(root==NULL)  return res;  
        if(root->left==NULL&&root->right==NULL){  
            res.push_back(to_string(root->val));  
            return res;  
        }  
        if(root->left!=NULL)  
           res=binaryTreePaths(root->left);  
        if(root->right!=NULL){  
            vector<string> tem;  
            tem=binaryTreePaths(root->right);  
            for(int i=0;i<tem.size();i++){  
                res.push_back(tem[i]);  
            }  
        }  
        for(int i=0;i<res.size();i++){  
            res[i]=to_string(root->val)+"->"+res[i];  
        }  
        return res;  
    }
};
發佈了128 篇原創文章 · 獲贊 8 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章