leetcode 94. Binary Tree Inorder Traversal

Posted ctqchina

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 94. Binary Tree Inorder Traversal相关的知识,希望对你有一定的参考价值。

求树的中序遍历,递归很简单,循环我用栈来实现,再用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的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode-94-Binary Tree Inorder Traversal]

[LeetCode]94.Binary Tree Inorder Traversal

leetcode 94. Binary Tree Inorder Traversal

LeetCode94 Binary Tree Inorder Traversal

LeetCode 94. Binary Tree Inorder Traversal

LeetCode 94: Binary Tree Inorder Traversal