Binary Tree Paths

本次的題目要求尋找樹根到葉子的所有路徑,並以string的方式輸出。基本思想上我所採用深度優先搜索算法(DP)解決樹的問題。

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"]
首先給出對樹節點的結構:

struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;    

TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  };

先給出主要搜索函數,創建存儲每一條路徑的vector path,初始先判斷根否為NULL,如果為空的話則返回當前path,我創建輔助搜索路徑的函數方便構想,其中利用DP算法實現。用to_string函數是為了將int類型轉換成string。

vector<string> binaryTreePaths(TreeNode* root) {
    vector<string> path;
    if(!root) 

return path;
    
    dp(path, root, to_string(root->val));
    return path;
}


在輔助搜索路徑的函數中,先判斷當前的樹節點有沒有左或右的孩子,如果都有則將當前節點以及之前紀錄的節點加入path的路徑紀錄中並返回。

如果否,則分別利用左右孩子繼續調用dp函數,直到判斷到中止。每次調用的時候都將入當前路徑已集結點的字符串,在終止處才將其存入path中。

void dp(vector<string>& path, TreeNode* root, string t) {
    if(!root->left && !root->right) {
        path.push_back(t);
        return;
    }


    if(root->left) 

dp(path, root->left, t + "->" + to_string(root->left->val));
    if(root->right)

dp(path, root->right, t + "->" + to_string(root->right->val));
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值