94. 二叉樹的中序遍歷(迭代)

Lazy mode發表於2020-10-04
/**
 * 94. 二叉樹的中序遍歷
 * @author wsq
 * @date 2020/10/04
 	給定一個二叉樹,返回它的中序 遍歷。

	示例:
	輸入: [1,null,2,3]
	   1
	    \
	     2
	    /
	   3
	輸出: [1,3,2]
	
	連結:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
 */
package com.wsq.tree;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class InorderTraversal {
    public List<Integer> inorderTraversal(TreeNode root) {
    	List<Integer> ans = new ArrayList();
        Deque<TreeNode> stack = new LinkedList();
        TreeNode pre = null;
        TreeNode curr = root;
        while(curr != null || !stack.isEmpty()){
            while(curr != null){
                stack.push(curr);
                curr = curr.left;
            }
            curr = stack.pop();
            ans.add(curr.val);
            curr = curr.right;
//            pre = curr;
//            if(curr.right != null && curr.right != pre){
//                curr = curr.right;
//            }else{
//                curr = null;
//            }

        }
        return ans;
    }
    
}

相關文章