leetcode
Java
Tree
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
給定一個N叉樹,輸出這個數每個節點依照階層由左至右,由上至下
Input: root = [1,null,3,2,4,null,5,6]
Output: [[1],[3,2,4],[5,6]]
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> result = new LinkedList<>();
if(root == null)
return result;
Queue<Node> queue = new LinkedList<Node>();
queue.offer(root);
while(!queue.isEmpty()){ // queue如果空了代表每個節點都poll
//一層迴圈代表處理一層level中的每個節點
List<Integer> level_result = new LinkedList<>();
int queue_size = queue.size(); //記錄這層的node個數
for (int i = 0;i < queue_size;i++){
Node n = queue.poll();
level_result.add(n.val);//將節點的value加到此層的list上
for (Node nn : n.children)//將目前此節點的children offer進去queue裏
queue.offer(nn);
}
result.add(level_result);
}
return result;
}
}
poll是將queue裡第一個節點提取出來並在queue中刪除此節點。 ↩︎
Description Given a string s, return the longest palindromic substring in s. 給定一個String,並找出最長的回文子字串(palindromic substring),如有多個相同長度的最長子字串可只回傳一個 Example Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer.
Aug 18, 2021Description The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
Aug 18, 2021Description Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). 將整數反轉,遇到超過32-bit的數就回傳0 Example Input: x = 123 Output: 321
Aug 15, 2021Description Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 給一字符串數組, 將錯位詞(指相同字符不同排列的字符串) 分組 Example Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Aug 15, 2021or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up