257. Binary Tree Paths

来源:互联网 发布:2017剑灵人男捏脸数据 编辑:程序博客网 时间:2024/05/22 13:50

Problem:

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”]

Analysis:
简单的二叉树遍历,遍历的过程中记录之前的路径,一旦遍历到叶子节点便将该路径加入结果中。

Answer:

// 未完成的用栈实现DFS代码/** * 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> result=new LinkedList<String>();        if(root==null) return result;        Stack<Integer> stack =new Stack<Integer>();        stack.add(root);        String path=root;        while(!stack.empty()){            TreeNode node = stack.pop();            if(node == root) path=path +'->'+node;            if(node.left ==null && node.right ==null)             path = path + node;            else if(node.left!=null)        }    }}
// 已完成的基于递归思想实现DFS的代码/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    List<String> result=new LinkedList<String>();    public List<String> binaryTreePaths(TreeNode root) {        if(root==null) return result;        else list_path(root,String.valueOf(root.val));        return result;    }    private void list_path(TreeNode root,String path){        if(root.left==null&&root.right==null){            result.add(path);        }        if(root.left!=null){            list_path(root.left,path+"->"+root.left.val);        }        if(root.right!=null){            list_path(root.right,path+"->"+root.right.val);        }    }}
0 0
原创粉丝点击