[LeetCode] 144. Binary Tree Preorder Traversal

题:https://leetcode.com/problems/binary-tree-preorder-traversal/description/

题目

Given a binary tree, return the preorder traversal of its nodes’ values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,2,3]

Follow up: Recursive solution is trivial, could you do it iteratively?

题目大意

实现 非递归 前序遍历。

思路

/**
 * 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> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if(root== null)
            return res;
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode curNode = stack.pop();
            res.add(curNode.val);
            if(curNode.right!=null)
                stack.push(curNode.right);
            if(curNode.left!=null)
                stack.push(curNode.left);
        }
        return res;
    }
}

统一 方法

/**
 * 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> preorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> res = new ArrayList<>();
        while(root!=null || !stack.isEmpty()){
            while(root!=null){
                res.add(root.val);
                stack.push(root);
                root = root.left;
            }
            if(!stack.isEmpty()){
                root = stack.pop();
                root = root.right;
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/83410598