面试笔试杂项积累-leetcode 246-260

来源:互联网 发布:centos 6.5 硬盘分区 编辑:程序博客网 时间:2024/06/18 14:01

257.257-Binary Tree Paths-Difficulty: Easy

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"]

思路

存储所有根到叶的路径,

深度优先遍历

左右子节点都为null时是一个路径到头了

/** * Definition for a binary tree node. * public class TreeNode { *     public int val; *     public TreeNode left; *     public TreeNode right; *     public TreeNode(int x) { val = x; } * } */public class Solution {   IList<string> fin = new List<string>();    public IList<string> BinaryTreePaths(TreeNode root)    {        getDeep(root, "");        return fin;    }    public void getDeep(TreeNode temp, string str)    {        if (temp != null)        {            if (temp.left == null && temp.right == null)                fin.Add(str + temp.val);            else            {                str += temp.val + "->";                if(temp.left!=null)                getDeep(temp.left, str);                if (temp.right != null)                getDeep(temp.right, str);             }        }    }}

258.258-Add Digits-Difficulty: Easy

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like:3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

Hint:

  1. A naive implementation of the above process is trivial. Could you come up with other methods?
  2. What are all the possible results?
  3. How do they occur, periodically or randomly?
  4. You may find thisWikipedia article useful.

方法一

思路

数字的每一位加在一起,直到加到个位数,返回个位数

转成string每一位加,直到位数为1

public class Solution {    public int AddDigits(int num) {           string str = num.ToString();        if (str.Length <= 1)            return num;        int temp = 0;        while (str.Length > 1)        {            temp = 0;            for (int i = 0; i < str.Length; i++)                temp += str[i] - '0';            str = temp.ToString();        }        return temp;    }}

方法二

思路

参考:

https://leetcode.com/discuss/80037/java-one-line-simple-answer

According to WIKI, we could compute the congruent root easily.

For number that from 0 to 9, the answer is themselves    

For number that is divisible by 9, the answer is 9    

Otherwise, the answer is the reminder after divided by 9


public int addDigits(int num) {    return num>9?(num%9==0?9:num%9):num;}



1 0