标签:return tree def 变量 bsp span 中序 实现 stack
求树的中序遍历,递归很简单,循环我用栈来实现,再用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; } }
leetcode 94. Binary Tree Inorder Traversal
标签:return tree def 变量 bsp span 中序 实现 stack
原文地址:https://www.cnblogs.com/ctqchina/p/10117214.html