Try   HackMD

【LeetCode】 257. Binary Tree Paths

Description

Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.

給一個二元樹,回傳所有從根到葉的路徑。
注意:葉子是只一個節點沒有任何小孩。

Example:

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

Solution

  • 超級基本的二元樹題目,用遞迴就輕鬆解。
  • 先將自己的值加入路徑中,接著判斷:
    • 如果自己沒有任何小孩,將路徑加入答案。
    • 如果有左子樹,遞迴call左邊。
    • 如果有右子樹,遞迴call右邊。
  • 需要注意:
    • 空的樹(root == NULL)
    • root的路徑不能有箭號在前面(你也可以在最後不加箭號在後面)

Code

/** * 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 addPath(TreeNode* node, string nowPath, vector<string>& allPath, bool first) { if(first) nowPath += to_string(node->val); else nowPath += "->" + to_string(node->val); if(node->right == NULL && node->left == NULL) allPath.push_back(nowPath); if(node->right) addPath(node->right, nowPath, allPath, false); if(node->left) addPath(node->left, nowPath, allPath, false); } vector<string> binaryTreePaths(TreeNode* root) { vector<string> allPath; if(root) addPath(root, string(), allPath, true); return allPath; } };
tags: LeetCode C++