1. 程式人生 > >Binary Tree Paths 二叉樹的所有路徑

Binary Tree Paths 二叉樹的所有路徑

給定一個二叉樹,返回所有從根節點到葉子節點的路徑。

說明: 葉子節點是指沒有子節點的節點。

示例:

輸入:

   1
 /   \
2     3
 \
  5

輸出: ["1->2->5", "1->3"]

解釋: 所有根節點到葉子節點的路徑為: 1->2->5, 1->3

這道題很簡單,用前序遍歷遍歷一遍樹便可以得到答案,主要是學會怎麼把遍歷到的節點拼接成字串,直接上程式碼:

   void binaryTreePathsCore(TreeNode* root, vector<string> &res, string val) {
	   if (root && !root->left && !root->right) {
		   res.push_back(val);
		   return;
	   }
	   if (root->left) {
		   binaryTreePathsCore(root->left, res, val + "->" + to_string(root->left->val));
	   }
	   if (root->right) {
		   binaryTreePathsCore(root->right, res, val + "->" + to_string(root->right->val));
	   }	   
   }

   vector<string> binaryTreePaths(TreeNode* root) {
	   vector<string> res;
	   if (!root) {
		   return res;
	   }
	   binaryTreePathsCore(root, res, to_string(root->val));
	   return res;
   }