LintCode: Binary Tree Paths

简介:

C++

复制代码
 1 /**
 2  * Definition of TreeNode:
 3  * class TreeNode {
 4  * public:
 5  *     int val;
 6  *     TreeNode *left, *right;
 7  *     TreeNode(int val) {
 8  *         this->val = val;
 9  *         this->left = this->right = NULL;
10  *     }
11  * }
12  */
13 class Solution {
14 public:
15     /**
16      * @param root the root of the binary tree
17      * @return all root-to-leaf paths
18      */
19     vector<string> binaryTreePaths(TreeNode* root) {
20         // Write your code here
21         vector<string> result;
22         if (root == NULL) {
23             return result;
24         }
25         string path="";
26         binaryTreePathsCore(root, result, path);
27         return result;
28     }
29     void binaryTreePathsCore(TreeNode* root, vector<string> &result, string path) {
30         if (root == NULL) {
31             return;
32         }
33         int i = root->val;
34         char a[5];
35         // itoa(i, a, 10);
36         sprintf(a, "%d", i);
37         if ("" == path) {
38             path = a;
39         } else {
40             path = path + "->" + a;
41         }
42         if (root->left == NULL && root->right == NULL) {
43             result.push_back(path);
44             return;
45         }
46         if (root->left != NULL) {
47             binaryTreePathsCore(root->left, result, path);
48         }
49         if (root->right != NULL) {
50             binaryTreePathsCore(root->right, result, path);
51         }
52         
53         
54     }
55 };
复制代码

 

本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/5000030.html,如需转载请自行联系原作者

相关文章
Leetcode 236. Lowest Common Ancestor of a Binary Tree
根据LCA的定义,二叉树中最小公共祖先就是两个节点p和q最近的共同祖先节点,LCA的定义没什么好解释的,主要是这道题的解法。
36 0
LeetCode 257. Binary Tree Paths
给定一个二叉树,返回所有从根节点到叶子节点的路径。 说明: 叶子节点是指没有子节点的节点。
57 0
LeetCode 257. Binary Tree Paths
LeetCode 105. Construct Binary Tree
给定一颗二叉树的前序和顺序遍历,构造原二叉树。 注意:您可以假设树中不存在重复项。
50 0
LeetCode 105. Construct Binary Tree
LeetCode 106. Construct Binary Tree
给定一颗二叉树的中序和后续遍历,构造原二叉树。 注意:您可以假设树中不存在重复项。
73 0
LeetCode 106. Construct Binary Tree
|
C++ Python
LeetCode 965. Univalued Binary Tree
LeetCode 965. Univalued Binary Tree
88 0
LeetCode 965. Univalued Binary Tree