leetcode 94. Binary Tree Inorder Traversal
阿新 • • 發佈:2018-12-14
求樹的中序遍歷,遞迴很簡單,迴圈我用棧來實現,再用hashmap或者改變變數的值來記錄一下。遞迴0ms,beats 100%,迴圈:改變值,1ms,beats 59.19%,用hashmap 2ms= =
只放迴圈的吧。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { LinkedList<Integer> ans = new LinkedList<>(); public List<Integer> inorderTraversal(TreeNode root) { Stack st = new Stack(); HashMap map = new HashMap(); TreeNode temp; if(root == null) return ans; st.add(root); while(st.isEmpty() != true){ temp = (TreeNode)st.peek(); if(temp.left != null){ st.add(temp.left); temp.left = null; continue; } ans.add(temp.val); st.pop(); if(temp.right != null) { st.add(temp.right); temp.right = null; } } return ans; } }