二叉树的所有路径

此博客链接:https://www.cnblogs.com/ping2yingshi/p/13449019.html

二叉树的所有路径

题目链接:https://leetcode-cn.com/problems/binary-tree-paths/

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

1
/ \
2 3
\
5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

题解:

       思路:

                1.需要定义一个列表。存储每次根到叶子节点的路径。

                2.定义两个队列,一个是存放层次遍历树中的节点,另外一个是存储字符串类型的路径,因为结果中包括箭头->。

                3.此题主要思路还是层次遍历,在层次遍历每次取出节点队列中的节点时,同时取出字符串队列中的路径,对节点进行判断,如果是叶子节点,则把字符串队列中的路径存到列表中,如果节点的左右子树存在,则把左右子树节点加入到队列中,并把子树节点的加入到字符串队列加上->后的队列中。

      代码:

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
       List<String> result = new ArrayList<>(); 
    if( root == null ) return result ; 
    Queue<TreeNode> treeQueue = new LinkedList<TreeNode>() ; 
    Queue<String> stringQueue = new LinkedList<String>() ; 
    treeQueue.offer(root) ; 
    stringQueue.offer(Integer.toString(root.val)); 
    while( !treeQueue.isEmpty()){
        int size = treeQueue.size(); 
        for( int i = 0 ; i < size ; ++i ) {
           TreeNode temp=treeQueue.poll();
           String tem=stringQueue.poll();
           if(temp.left==null&&temp.right==null)
           {
               result.add(tem);
           }
           if(temp.left!=null)
           {
               treeQueue.add(temp.left);
               String  str=tem+"->"+temp.left.val;
                stringQueue.add(str);
           }
           if(temp.right!=null)
           {
               treeQueue.add(temp.right);
               String  str=tem+"->"+temp.right.val;
                stringQueue.add(str);
           }
          }
 
    }
       return result ; 
}
}

 

           

 

posted @ 2020-08-06 21:09  萍2樱释  阅读(144)  评论(0编辑  收藏  举报