LeetCode刷题Easy篇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

十分钟尝试

二叉树的两个杀手锏,一个是递归,处理复杂的问题,一个是DFS和BFS的搭建的遍历二叉树的迭代代码结构,增加一个个性化逻辑处理二叉树问题。很显然这个问题可以用递归解决。有个问题一定要注意,递归调用的时候path不要写+=,这样会修改path的值,调用完左侧,调用右侧的时候结果不正确。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> list=new ArrayList();
        if(root==null) return list;
        String path="";
        searchPath(path,root,list);
        return list;
    }
    public void searchPath(String path,TreeNode node,List<String> res){
        if(node.left==null&&node.right==null){
            res.add(path+=node.val);
        }
        if(node.left!=null){
            //不要写path加上等于,否则会修改path的值,右侧会发生变化,这样path一直为空
             searchPath(path+node.val+"->",node.left,res);
        }
        if(node.right!=null){
             searchPath(path+node.val+"->",node.right,res);
        }
       
        
        
    }
}

猜你喜欢

转载自blog.csdn.net/hanruikai/article/details/85061175