zoukankan      html  css  js  c++  java
  • lintcode480- Binary Tree Paths- easy

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

    Example

    Given the following binary tree:

       1
     /   
    2     3
     
      5
    

    All root-to-leaf paths are:

    [
      "1->2->5",
      "1->3"
    ]
    Tags 
    Binary Tree Facebook Binary Tree Traversal Google

    分治法。注意一下叶子节点和null节点这次处理不太一样而已。

    1.如果是list<String> result; 不能直接result.add(Integer)!但result.add("" + Integer);可以。 result.add(Integer + s)也可以。不能直接塞一个其他类型,前面加空或者其他部分有加该类型是帮你说了要类型转换。

    /**
     * Definition of TreeNode:
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left, right;
     *     public TreeNode(int val) {
     *         this.val = val;
     *         this.left = this.right = null;
     *     }
     * }
     */
    
    
    public class Solution {
        /*
         * @param root: the root of the binary tree
         * @return: all root-to-leaf paths
         */
        public List<String> binaryTreePaths(TreeNode root) {
            // write your code here
            
            List<String> result = new ArrayList<String>();
            
            if (root == null) {
                return result;
            }
            
            if (root.left == null && root.right == null) {
                result.add("" + root.val);
                return result;
            }
            
            List<String> left = binaryTreePaths(root.left);
            List<String> right = binaryTreePaths(root.right);
            for (String s : left) {
                result.add(root.val + "->" + s);
            }
            for (String s : right) {
                result.add(root.val + "->" + s);
            }
            return result;
        }
    }
    
    
  • 相关阅读:
    MSN无法登录(错误代码80072745)的解决方法
    C#3.0新体验(二) 扩展方法
    My DreamTech
    让IE崩溃的bug, IE8也一样崩溃
    多线程的相关概念
    10条PHP经验总结
    PHP框架 CI与TP之MVC比较
    多线程设计要点
    Linux yum命令的使用技巧
    BigPipe 的工作原理
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7637357.html
Copyright © 2011-2022 走看看