和我一起迎接明天的太阳吧

klaus08

焦虑源于行动的匮乏

二叉树的迭代遍历

转自 https://leetcode-cn.com/problems/binary-tree-inorder-traversal/solution/yan-se-biao-ji-fa-yi-chong-tong-yong-qie-jian-ming/



一般的迭代遍历比较难理解,今天看到了一种“通法”。

package com.klaus.prob94;

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

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    List<Integer> res = new ArrayList<>();

    class Node {
        TreeNode treeNode;
        boolean flag;

        public Node(TreeNode treeNode, boolean flag) {
            this.treeNode = treeNode;
            this.flag = flag;
        }
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        if (root == null) return res;
        LinkedList<Node> stack = new LinkedList<>();

        stack.push(new Node(root, false));

        while (!stack.isEmpty()) {
            Node node = stack.pop();
            if (!node.flag) {
                if (node.treeNode.right != null) stack.push(new Node(node.treeNode.right, false));
                stack.push(new Node(node.treeNode, true));
                if (node.treeNode.left != null) stack.push(new Node(node.treeNode.left, false));
            } else {
                res.add(node.treeNode.val);
            }
        }

        return res;
    }
}
posted @ 2021-10-31 10:15  klaus08  阅读(24)  评论(0编辑  收藏  举报