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;
    }
}

猜你喜欢

转载自www.cnblogs.com/ctqchina/p/10117214.html