Binary Tree Preorder Traversal Java版本

原创 2015年07月06日 16:57:45
二叉树先序遍历
思路:

     不使用递归前序遍历,可以借助栈的帮助实现。对于一个特定节点,前序遍历顺序为: 根,左,右。所以入栈顺序为 右,左,根。由于根节点的遍历和展开(研究其右节点和左  节点)是同时的,所以根节点出栈的同时即可加入遍历结果中,然后研究其右节点和左节点,如果不为空即可入栈。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
  public ArrayList<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> returnList = new ArrayList<Integer>();
 
        if(root == null)
            return returnList;
 
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
 
        while(!stack.empty()){
            TreeNode n = stack.pop();
            returnList.add(n.val);
 
            if(n.right != null){
                stack.push(n.right);
            }
            if(n.left != null){
                stack.push(n.left);
            }
 
        }
        return returnList;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

【LeetCode-面试算法经典-Java实现】【105-Construct Binary Tree from Preorder and Inorder Traversal(构造二叉树)】

【106-Construct Binary Tree from Preorder and Inorder Traversal(通过前序和中序遍历构造二叉树)】【LeetCode-面试算法经典-Java...

[leetcode]105. Construct Binary Tree from Preorder and Inorder Traversal@Java解题报告

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/...

LeetCode 144 — Binary Tree Preorder Traversal(C++ Java Python)

题目:http://oj.leetcode.com/problems/binary-tree-preorder-traversal/ Given a binary tree, return the p...

Construct Binary Tree from Preorder and Inorder Traversal (Java)

Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume ...

Binary Tree Preorder Traversal (Java)

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

LeetCode#105. Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal...

LeetCode | Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values. For example: Given bina...

Construct Binary Tree from Preorder and Inorder Traversal LeetCode 105

题目描述: Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may as...

[LeetCode] Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes’ values.For example: Given binary t...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)