• LeetCode_257. Binary Tree Paths


    257. Binary Tree Paths

    Easy

    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
    package leetcode.easy;
    
    /**
     * Definition for a binary tree node. public class TreeNode { int val; TreeNode
     * left; TreeNode right; TreeNode(int x) { val = x; } }
     */
    public class BinaryTreePaths {
    	java.util.List<String> list = new java.util.LinkedList<>();
    
    	public java.util.List<String> binaryTreePaths(TreeNode root) {
    		path(root, "");
    		return list;
    	}
    
    	private void path(TreeNode root, String str) {
    		if (null == root) {
    			return;
    		}
    		str = str + "->" + root.val;
    		if (null == root.left && null == root.right) {
    			list.add(str.substring(2));
    			return;
    		}
    		path(root.left, str);
    		path(root.right, str);
    	}
    
    	@org.junit.Test
    	public void test() {
    		TreeNode node11 = new TreeNode(1);
    		TreeNode node21 = new TreeNode(2);
    		TreeNode node22 = new TreeNode(3);
    		TreeNode node32 = new TreeNode(5);
    		node11.left = node21;
    		node11.right = node22;
    		node21.left = null;
    		node21.right = node32;
    		node22.left = null;
    		node22.right = null;
    		node32.left = null;
    		node32.right = null;
    		System.out.println(binaryTreePaths(node11));
    	}
    }
    
  • 相关阅读:
    eclipse 不自动提示和Alt + / 没提示和eclipse增强代码提示
    uboot 添加命令
    ps and kill command
    C 类型volatile 的作用
    git tutorial
    python 与命令
    C++ new and delete
    Glade3 tutorial in chinese
    查找IP与MAC
    ns3 无线资料
  • 原文地址:https://www.cnblogs.com/denggelin/p/11764860.html
Copyright © 2020-2023  润新知