leetcode:144. Binary Tree Preorder Traversal

转载请注明出处:z_zhaojun的博客
原文地址
题目地址
Binary Tree Preorder Traversal

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

For example:
Given binary tree {1,#,2,3},
return [1,2,3].

思路:优先添加遍历左子树,在遍历的同时判断当前节点的右子树是否为空,如果不为空则添加到nodeList(类似栈,实现先进后出,最晚add的最先remove)中,当左子树遍历完毕后,再通过nodeList进行右子树的遍历。
实现代码(Java):

public class Solution {
    public List preorderTraversal(TreeNode root) {
        List valList = new ArrayList<>();
        List nodeList = new ArrayList<>();
        while (root != null) {
            valList.add(root.val);
            if (root.right != null) {
                nodeList.add(root.right);
            }
            if (root.left != null) {
                root = root.left;
            } else {
                if (nodeList.size() > 0) {
                    root = nodeList.get(nodeList.size() - 1);
                    nodeList.remove(nodeList.size() - 1);
                } else {
                    break;
                }
            }
        }
        return valList;
    }
}

你可能感兴趣的:(LeetCode,android初级进阶,leetcode算法分析)