zoukankan      html  css  js  c++  java
  • 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

    backtracking, 记得返回上层的时候删掉该层节点

    time: O(n)   -- visited each node exactly once, space: O(logn)  -- worst case: O(n) unbalanced tree

    /**
     * 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> res = new ArrayList<>();
            if(root == null) {
                return res;
            }
            dfs(root, new StringBuilder(), res);
            return res;
        }
        
        public void dfs(TreeNode root, StringBuilder sb, List<String> res) {
            if(root == null) {
                return;
            }
            int len = sb.length();
            sb.append(root.val);
            if(root.left == null && root.right == null) {
                res.add(sb.toString());
                sb.delete(len, sb.length());
                return;
            }
            
            sb.append("->");
            
            dfs(root.left, sb, res);
            dfs(root.right, sb, res);
            sb.delete(len, sb.length());
        }
    }
  • 相关阅读:
    Java数据结构之栈(Stack)
    Java数据结构之单向环形链表(解决Josephu约瑟夫环问题)
    Java数据结构之双向链表
    zookeeper:JavaApi操作节点
    zookeeper:3
    单例模式
    zookeeper:2
    架构版本
    zookeeper:1
    Java反射
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10190653.html
Copyright © 2011-2022 走看看