二叉树--路径

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

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值