144.二叉树的前序遍历(二叉树,简单)

题目链接

给你二叉树的根节点 root ,返回它节点值的 前序 遍历。

示例 1:
输入:root = [1,null,2,3]
输出:[1,2,3]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:
输入:root = [1,2]
输出:[1,2]
示例 5:
输入:root = [1,null,2]
输出:[1,2]
提示:
  • 树中节点数目在范围 [0, 100] 内
  • -100 <= Node.val <= 100
进阶:递归算法很简单,你可以通过迭代算法完成吗?

解答

/**
 * Definition for a binary tree node.
 * public 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;
 *     }
 * }
 */
class Solution {
    public List preorderTraversal(TreeNode root) {
        // 递归解法
        /*List result = new ArrayList<>();
        if (root == null) return result;
        result.add(root.val);
        result.addAll(preorderTraversal(root.left));
        result.addAll(preorderTraversal(root.right));
        return result;*/
        // 迭代解法
        List result = new ArrayList<>();
        Stack nodeQueue = new Stack<>();
        nodeQueue.push(root);
        if (root == null) return result;
        result.add(root.val);
        TreeNode node;
        while (!nodeQueue.isEmpty()) {
            node = nodeQueue.peek();
            if (node.left != null)
                nodeQueue.push(node.left);
            else if (node.right != null)
                nodeQueue.push(node.right);
            else {
                nodeQueue.pop();
                while (!nodeQueue.isEmpty() && 
                (nodeQueue.peek().right == node || (node=nodeQueue.peek().right) == null))
                    node = nodeQueue.pop();
                if (nodeQueue.isEmpty()) break;
                nodeQueue.push(node);
            }
            result.add(nodeQueue.peek().val);
        }
        return result;
    }
}

你可能感兴趣的:(144.二叉树的前序遍历(二叉树,简单))