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

    Question:

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

    For example, given the following binary tree:

       1
     /   
    2     3
     
      5
    

    All root-to-leaf paths are:

    ["1->2->5", "1->3"]

     Analysis:

    问题描述:给出一棵二叉树,给出所有根节点到叶子节点的路径。

    思路一:递归

    Answer:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        List<String> res = new ArrayList<String>();
        public List<String> binaryTreePaths(TreeNode root) {
            if(root != null)
                findPath(root, Integer.toString(root.val));
            return res;
        }
        
        public void findPath(TreeNode root, String string) {
            // TODO Auto-generated method stub
            if(root.left == null && root.right == null)
                res.add(string);
            if(root.left != null)
                findPath(root.left, string + "->" + Integer.toString(root.left.val));
            if(root.right != null)
                findPath(root.right, string + "->" + Integer.toString(root.right.val));
        }
    }

    思路二:深度优先遍历,用栈保存遍历过的节点。

  • 相关阅读:
    Sass变量、嵌套
    遮罩层2
    遮罩层
    大图轮播
    项目资料(主页)
    关于时间控制和制定时间日期
    dom作业
    js的dom操作和函数
    js数组去重
    js For循环练习。
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4844331.html
Copyright © 2011-2022 走看看