非遞歸實現二叉樹的中序遍歷

在這裏插入圖片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    public List<Integer> inorderTraversal(TreeNode root) {
        List res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        while(root != null || !stack.isEmpty() ){
            while(root != null){
                stack.push(root);
                root = root.left;
            }
            root = (stack.pop());
            res.add(root.val);
            root = root.right;

        }
        return res;
    }
}
發佈了124 篇原創文章 · 獲贊 9 · 訪問量 2476
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章