Thursday, December 3, 2015

Binary Tree Paths

Q:
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"]
A:  
递归,同时传入路径作为String参数
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> list = new LinkedList();
        if(root != null)
            helper(list,"",root);
        return list;
    }
    private void helper( List<String> list, String pre, TreeNode root){
        pre = pre + "->"+root.val;
        if(root.left == null && root.right == null)
            list.add(pre.substring(2));
        if(root.left != null)
            helper(list,pre,root.left);
        if(root.right != null)
            helper(list,pre ,root.right);
    }
}


*************2nd pass**********没有用helper Function*********

/**
 * 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:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if(!root)
            return res;
        auto L = binaryTreePaths(root->left);
        auto R = binaryTreePaths(root->right);
        for(auto s: L)
            res.push_back(to_string(root->val)+"->"+s);
        
        for(auto s: R)
            res.push_back(to_string(root->val)+"->"+s);
        
        if(res.empty())
            res.push_back(to_string(root->val));
        
        return res;
    }
};




********Iteratively,  using a stack ****************
但是这样,需要考虑该节点只有一个child 都情况,因此需要判断其有几个child。





No comments:

Post a Comment