【Leetcode】Binary Tree Paths 二叉树根结点到所有叶子结点的路径

Leetcode Binary Tree Paths 二叉树根结点到所有叶子结点的路径

package ac.leetcode.tree;

import org.junit.Test;

import java.util.LinkedList;
import java.util.List;

/**
 * description:
 *
 * @author liyazhou
 * @since 2017-07-02 10:45
 *
 *  Binary Tree Paths
 *
 * 题目:
 *  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"]
 */
public class BinaryTreePaths {
    private static class BinTreeNode{
        int value;
        BinTreeNode left;
        BinTreeNode right;

        public BinTreeNode (int _value){ value = _value; }
        public void setChildren(BinTreeNode _left, BinTreeNode _right){
            left = _left;
            right = _right;
        }
    }


    public List<String> binaryTreePaths(BinTreeNode root){
        List<String> paths = new LinkedList<>();
        if (root == null) return paths; // if root == null, return []
        String path = "";
        binaryTreePaths(root, paths, path);
        return paths;
    }

    private void binaryTreePaths(BinTreeNode root, List<String> paths, String path) {
        if (root == null) return;

        // 叶子结点,路径中的末尾结点,是专有的
        if (root.left == null && root.right == null){
            if ("".equals(path))  path += root.value;
            else                  path += "->" + root.value;
            paths.add(path);
            return;
        }

        // 根结点到当前结点的路径,为其左右子结点公有的路径
        if ("".equals(path)) path += root.value;
        else                 path += "->"+root.value;
        binaryTreePaths(root.left, paths, path);
        binaryTreePaths(root.right, paths, path);
    }


    @Test
    public void test(){
        BinTreeNode node1 = new BinTreeNode(1);
        BinTreeNode node2 = new BinTreeNode(2);
        BinTreeNode node3 = new BinTreeNode(3);
        BinTreeNode node5 = new BinTreeNode(5);

        node1.setChildren(node2, node3);
        node2.setChildren(null, node5);

        List<String> paths = binaryTreePaths(node1);
        for (String path : paths)
            System.out.println(path);
    }
}
对于一棵树的后序遍历,我们首先遍历左子树,然后遍历右子树,最后访问节点据这个顺序,我们可以借助一个栈来完成。 假设要输出节点root到某一结点target的路径,首先,我们将root节点入栈。然后,进行以下循环: 1. 将栈顶节点弹出; 2. 如果栈顶节点的值等于target的值,则说明找到了目标结点,结束循环; 3. 如果栈顶节点的右子树不为空且右子树未被访问过,则将右子树入栈; 4. 如果栈顶节点的左子树不为空且左子树未被访问过,则将左子树入栈; 5. 如果栈顶节点的左右子树都为空,说明该结点叶子节点,将其出栈。 最终,栈中保存的结点序列就是节点到目标结点路径。 下面是一个示例代码,假设树的节点定义如下: ```python class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None ``` ```python def postorderPath(root, target): if root is None: return [] stack = [] result = [] visited = set() stack.append(root) while stack: node = stack[-1] if node in visited: stack.pop() result.pop() else: visited.add(node) result.append(node.val) if node.val == target: break if node.right and node.right not in visited: stack.append(node.right) if node.left and node.left not in visited: stack.append(node.left) return result ``` 这样,调用`postorderPath(root, target)`函数即可得到节点root到目标结点target的路径
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值