zoukankan      html  css  js  c++  java
  • 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));
    	}
    }
    
  • 相关阅读:
    Block & 代理
    堆&栈, 内存分配
    ASI 的 使用
    iOS开发-清理缓存功能的实现
    iOS8是如何跳转系统设置页面
    键盘弹出获取高度
    http://www.jianshu.com/collection/9a22b04a9357
    IOS 字符串中去除特殊符号 stringByTrimmingCharactersInSet
    iOS 判断输入是否全是空格
    iOS AFN 请求封装方法
  • 原文地址:https://www.cnblogs.com/denggelin/p/11764860.html
Copyright © 2011-2022 走看看