日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【Leetcode】103. 二叉树的锯齿形层次遍历

發布時間:2025/7/14 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Leetcode】103. 二叉树的锯齿形层次遍历 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目

給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。

例如:
給定二叉樹 [3,9,20,null,null,15,7],

3/ \9 20/ \15 7

返回鋸齒形層次遍歷如下:

[[3],[20,9],[15,7] ]

題解

這道題要求用z字型,就是要求知道深度。因為知道深度我們就可以根據深度的奇偶來判斷如何打印。
首先相到的就是層序遍歷,然后記錄是第幾層。層序遍歷用隊列的代碼我們已經很熟悉了。

/*** 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<>();// 當前層一直出隊.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);}// 奇數層,從頭添加; 偶數層從尾部添加.if (depth % 2 != 0) {currentRes.add(0, current.val);} else {currentRes.add(current.val);}size--;}// 把當前層遍歷的結果加入到結果中.res.add(currentRes);depth++;}return res;} }

同之前一樣,我們想一想有沒有遞歸的解法.
我們可以采用先序遍歷的方式,先遍歷節點,然后遞歸的遍歷左子樹和右子樹。
稍作改動的是,需要在遍歷左子樹和右子樹的時候帶上深度的信息,才能知道是加在列表頭還是列表尾部。
遞歸的結束條件就是遇到空節點。

/*** 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, 說明當前節點遞歸進入了新的層.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);} }

熱門閱讀

  • 技術文章匯總
  • 【Leetcode】101. 對稱二叉樹
  • 【Leetcode】100. 相同的樹
  • 【Leetcode】98. 驗證二叉搜索樹

總結

以上是生活随笔為你收集整理的【Leetcode】103. 二叉树的锯齿形层次遍历的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。