【LeetCode】【94】【Binary Tree Inorder Traversal】

题目:Given a binary tree, return the inorder traversal of its nodes’ values.
解题思路:树的非递归遍历,先序,中序,后序都用栈,层序用队列。建议最好写非递归的
代码:

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
    }
}
    public List<Integer> inorderTraversal(TreeNode root) {
        //非递归中序遍历
        Stack<TreeNode> stack = new Stack<>();
        ArrayList<Integer> ans = new ArrayList<>();
        if(root == null)  return ans;
        while (root !=null ||!stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            if (!stack.isEmpty()) {
                root = stack.pop();
                ans.add(root.val);
                root = root.right;
            }
        }
        return ans;
    }

猜你喜欢

转载自blog.csdn.net/u012503241/article/details/82924119