二叉树的非递归遍历

為{幸葍}努か 提交于 2019-12-16 13:53:10

https://yuanyu.blog.csdn.net/article/details/102639318 


1 系统栈调用过程 

 

 

 

 

 

 

 

 

 

 

 


2 coding

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) {
        val = x;
    }
}
/**
 * 144. 二叉树的前序遍历:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
 * 94. 二叉树的中序遍历:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
 * 145. 二叉树的后序遍历:https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
 */
public class Solution {
    private static class Command {
        String s;   // go, print
        TreeNode node;
        Command(String s, TreeNode node) {
            this.s = s;
            this.node = node;
        }
    }
    //preorderTraversal
    //inorderTraversal
    //postorderTraversal
    public List<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Deque<Command> stack = new ArrayDeque<>();
        stack.push(new Command("go", root));
        while (!stack.isEmpty()) {
            Command command = stack.pop();
            if (command.s.equals("print")) {
                res.add(command.node.val);
            } else {//command.s.equals("go");
                //后序遍历 stack.push(new Command("print", command.node));
                if (command.node.right != null) {
                    stack.push(new Command("go", command.node.right));
                }
                //中序遍历 stack.push(new Command("print", command.node));
                if (command.node.left != null) {
                    stack.push(new Command("go", command.node.left));
                }
                //前序遍历 stack.push(new Command("print", command.node));
            }
        }
        return res;
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!