leetcode题解(257) Binary Tree Paths(打印所有二叉树根节点到叶节点的路径)

题目描述:

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

解题思路:这题说是简单题,其实如果不经常做回溯的问题也不容易一下做出来,设置一个列表或者StringBuffer用来存储根节点到当下节点的路径,然后依次深度优先遍历,判断遍历到节点是否是叶子节点,如果是,把列表或者StringBuffer存储到List中

代码如下:

class Solution {
    public int len;
    public List binaryTreePaths(TreeNode root) {
        List list = new ArrayList<>();
        if(root == null){
            return list;
        }
        StringBuilder sb = new StringBuilder();
        len = (root.val + "").length();
        backtracking(list, root, sb);
        return list;
    }
    public void backtracking(List list, TreeNode root, StringBuilder sb){
        if(root != null){
            if(sb.length() == 0)
                sb.append(root.val + "");
            else
                sb.append("->" + root.val);
        }else{
            return;
        }
        
        if(isLeaf(root)){
            list.add(sb.toString());
        }else{
            backtracking(list, root.left, sb);
            backtracking(list, root.right, sb);
        } 
        if(sb.length() != len)
            sb.delete(sb.length() - ("->"+root.val).length(), sb.length());
    }
    
    public boolean isLeaf(TreeNode node){
        return (node.left == null && node.right == null);
    }
    
}

 

你可能感兴趣的:(java,数据结构与算法,刷题)