码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 94. Binary Tree Inorder Traversal

时间:2018-12-14 00:51:53      阅读:217      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!