Lintcode:二叉樹的所有路徑

問題:

給一棵二叉樹,找出從根節點到葉子節點的所有路徑。

樣例:

樣例 1:

輸入:{1,2,3,#,5}
輸出:["1->2->5","1->3"]
解釋:
   1
 /   \
2     3
 \
  5

樣例 2:

輸入:{1,2}
輸出:["1->2"]
解釋:
   1
 /   
2     

python:

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: the root of the binary tree
    @return: all root-to-leaf paths
    """
    def findLastNode(self, root, path, result):
        if root == None:
            return None
        path += str(root.val)
        if root.left == None and root.right == None:
            result.append(path)
        else:
            path += "->"
            if root.left != None:
                self.findLastNode(root.left, path, result)
            if root.right != None:
                self.findLastNode(root.right, path, result)
                
    def binaryTreePaths(self, root):
        # write your code here
        if root == None:
            return []
        path = ""
        result = []
        self.findLastNode(root, path, result)
        return result

C++:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the root of the binary tree
     * @return: all root-to-leaf paths
     */
    void findLastNode(TreeNode *root, string path, vector<string> &result)
    {
        if(root == NULL)
        {
            return;
        }
        path += to_string(root->val);
        if(root->left == NULL && root->right == NULL)
        {
            result.push_back(path);
        }else{
            path += "->";
            if(root->left != NULL)
            {
                findLastNode(root->left, path, result);
            }
            if(root->right != NULL)
            {
                findLastNode(root->right, path, result);
            }
        }
    }
    vector<string> binaryTreePaths(TreeNode * root) {
        // write your code here
        if(root == NULL)
        {
            return vector<string>();
        }
        string path = "";
        vector<string> result;
        findLastNode(root, path, result);
        return result;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章