二叉树--路径

来源:互联网 发布:node服务器优点 编辑:程序博客网 时间:2024/05/16 18:09

二叉树中,从根节点到叶节点的每一条连接,我们称之为路径,最短路径和最长路径在之前的博客中,我们已经完成了对他们的讨论,现在我们讨论一下,输出一棵二叉树中全部的路径信息。代码如下所示:

public class Operation{    List<String> result = new LinkedList<String>();//存储最后的结果    public List<String> binaryTreePaths(TreeNode root) {        if (root == null) {            return result;        }        childBinaryTreePath(root, "");        return result;    }    public void childBinaryTreePath(TreeNode root, String path) {        path += root.val;        if (root.left == null && root.right == null) {            result.add(path);//叶子节点,将整条路径加入到结果集中        }         //将所有路径按照从左到右的顺序来进行存储,        if (root.left != null) {            childBinaryTreePath(root.left, path + "->");        }        if (root.right != null) {            childBinaryTreePath(root.right, path + "->");        }    }}

下面是非递归的方式:

public List<String> binaryTreePaths2(TreeNode root) {//利用栈来进行输出    Stack<Pair<TreeNode, String>> stack = new Stack<>();    stack.push(new Pair(root, ""));    List<String> ret = new ArrayList<>();    while (!stack.isEmpty()) {        Pair<TreeNode, String> p = stack.pop();        TreeNode n = p.getKey();        String str = p.getValue();        if (n != null) {            if (n.left == null && n.right == null) {                str += Integer.toString(n.val);                ret.add(str);            }            //从左到右的顺序            stack.push(new Pair(n.right, str+n.val+"->"));            stack.push(new Pair(n.left, str+n.val+"->"));        }    }    return ret;}public List<String> binaryTreePaths(TreeNode root) {    Queue<Pair<TreeNode, String>> queue = new LinkedList<>();//利用队列    queue.add(new Pair(root, ""));    List<String> ret = new LinkedList<>();    while (!queue.isEmpty()) {        Pair<TreeNode, String> p = queue.poll();        TreeNode n = p.getKey();        String str = p.getValue();        if (n != null) {            if (n.left == null && n.right == null) {                str += n.val;                ret.add(str);                //continue;            }            //依然是从左到右            queue.add(new Pair(n.left, str+n.val+"->"));            queue.add(new Pair(n.right, str+n.val+"->"));        }    }    return ret;}

非递归思想:利用栈或者是队列,节点不为空,进栈,并且存储路径信息,然后出栈判断,如果为叶子节点,那么加入到结果集中,否则,继续存储;数据结构Pair存储的下一个节点+到该节点父节点的整个路径。

1 0
原创粉丝点击