生活随笔
收集整理的這篇文章主要介紹了
【Leetcode】103. 二叉树的锯齿形层次遍历
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目
給定一個(gè)二叉樹(shù),返回其節(jié)點(diǎn)值的鋸齒形層次遍歷。(即先從左往右,再?gòu)挠彝筮M(jìn)行下一層遍歷,以此類推,層與層之間交替進(jìn)行)。
例如:
給定二叉樹(shù) [3,9,20,null,null,15,7],
3/ \9 20/ \15 7
返回鋸齒形層次遍歷如下:
[[3],[20,9],[15,7]
]
題解
這道題要求用z字型,就是要求知道深度。因?yàn)橹郎疃任覀兙涂梢愿鶕?jù)深度的奇偶來(lái)判斷如何打印。
首先相到的就是層序遍歷,然后記錄是第幾層。層序遍歷用隊(duì)列的代碼我們已經(jīng)很熟悉了。
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {public List<List<Integer>> zigzagLevelOrder(TreeNode root) {List<List<Integer>> res = new LinkedList<>();if (root == null) {return res;}LinkedList<TreeNode> queue = new LinkedList<>();queue.add(root);int depth = 0;while (!queue.isEmpty()) {int size = queue.size();LinkedList<Integer> currentRes = new LinkedList<>();// 當(dāng)前層一直出隊(duì).while (size > 0) {TreeNode current = queue.poll();TreeNode left = current.left;TreeNode right = current.right;if (left != null) {queue.add(left);}if (right != null) {queue.add(right);}// 奇數(shù)層,從頭添加; 偶數(shù)層從尾部添加.if (depth % 2 != 0) {currentRes.add(0, current.val);} else {currentRes.add(current.val);}size--;}// 把當(dāng)前層遍歷的結(jié)果加入到結(jié)果中.res.add(currentRes);depth++;}return res;}
}
同之前一樣,我們想一想有沒(méi)有遞歸的解法.
我們可以采用先序遍歷的方式,先遍歷節(jié)點(diǎn),然后遞歸的遍歷左子樹(shù)和右子樹(shù)。
稍作改動(dòng)的是,需要在遍歷左子樹(shù)和右子樹(shù)的時(shí)候帶上深度的信息,才能知道是加在列表頭還是列表尾部。
遞歸的結(jié)束條件就是遇到空節(jié)點(diǎn)。
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {public List<List<Integer>> zigzagLevelOrder(TreeNode root) {List<List<Integer>> res = new LinkedList<>();if (root == null) {return res;}helper(res, root, 0);return res;}public void helper(List<List<Integer>> res,TreeNode root, int depth) {if (root == null) {return;}// 注意這里new List, 說(shuō)明當(dāng)前節(jié)點(diǎn)遞歸進(jìn)入了新的層.if (res.size() <= depth) {res.add(new LinkedList<>());}if (depth % 2 != 0) {res.get(depth).add(0, root.val);} else {res.get(depth).add(root.val);}helper(res, root.left, depth + 1);helper(res, root.right, depth + 1);}
}
熱門閱讀
- 技術(shù)文章匯總
- 【Leetcode】101. 對(duì)稱二叉樹(shù)
- 【Leetcode】100. 相同的樹(shù)
- 【Leetcode】98. 驗(yàn)證二叉搜索樹(shù)
總結(jié)
以上是生活随笔為你收集整理的【Leetcode】103. 二叉树的锯齿形层次遍历的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。