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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

leetcode94 二叉树的中序遍历

發布時間:2023/12/13 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode94 二叉树的中序遍历 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

給定一個二叉樹,返回它的中序?遍歷。

示例:

輸入: [1,null,2,3]
? ?1
? ? \
? ? ?2
? ? /
? ?3

輸出: [1,3,2]
進階:?遞歸算法很簡單,你可以通過迭代算法完成嗎?

遞歸

/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ class Solution {public List < Integer > inorderTraversal(TreeNode root) {List < Integer > res = new ArrayList < > ();helper(root, res);return res;}public void helper(TreeNode root, List < Integer > res) {if(root == null)return;helper(root.left, res);res.add(root.val);helper(root.right, res);} }

壓棧

public class Solution {public List < Integer > inorderTraversal(TreeNode root) {List < Integer > res = new ArrayList < > ();Stack < TreeNode > stack = new Stack < > ();TreeNode curr = root;while (curr != null || !stack.isEmpty()) {while (curr != null) {stack.push(curr);curr = curr.left;}curr = stack.pop();res.add(curr.val);curr = curr.right;}return res;} }

morris

雖然是空間O(1),但是oj并沒有測出來效果,依舊空間只超過40%

/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ class Solution {public List < Integer > inorderTraversal(TreeNode root) {List < Integer > res = new ArrayList < > ();TreeNode curr = root;TreeNode pre;while (curr != null) {if (curr.left == null) {res.add(curr.val);curr = curr.right; // move to next right node} else { // has a left subtreepre = curr.left;while (pre.right != null) { // find rightmostpre = pre.right;}pre.right = curr; // put cur after the pre nodeTreeNode temp = curr; // store cur nodecurr = curr.left; // move cur to the top of the new treetemp.left = null; // original cur left be null, avoid infinite loops}}return res;} }

?

總結

以上是生活随笔為你收集整理的leetcode94 二叉树的中序遍历的全部內容,希望文章能夠幫你解決所遇到的問題。

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