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

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 this Wikipedia 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;
}



评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值