leetcode94 二叉树的中序遍历
生活随笔
收集整理的這篇文章主要介紹了
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 二叉树的中序遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leecode26 删除排序数组中的重复
- 下一篇: 简单暴力到dp的优化(入门篇)