Binary Tree Preorder Traversal

Binary Tree Preorder Traversal 

问题:

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

Recursive solution is trivial, could you do it iteratively?

思路:

  栈的方法 弹出栈顶的时候 先加入有节点 再加入做节点 直到栈空

我的代码:

public class Solution {

    public List<Integer> preorderTraversal(TreeNode root) {

        List<Integer> list = new ArrayList<Integer>();

        if(root == null)    return list;

        Stack<TreeNode> stack = new Stack<TreeNode>();  

        stack.push(root);

        do

        {

            TreeNode node = stack.pop();

            list.add(node.val);

            if(node.right != null)  stack.push(node.right);

            if(node.left != null)   stack.push(node.left);

        }while(!stack.isEmpty());

        return list;

    }

}
View Code

他人代码:

public class Solution {

    public List<Integer> preorderTraversal(TreeNode root) {

        Stack<TreeNode> stack = new Stack<TreeNode>();

        List<Integer> preorder = new ArrayList<Integer>();

        

        if (root == null) {

            return preorder;

        }

        

        stack.push(root);

        while (!stack.empty()) {

            TreeNode node = stack.pop();

            preorder.add(node.val);

            if (node.right != null) {

                stack.push(node.right);

            }

            if (node.left != null) {

                stack.push(node.left);

            }

        }

        

        return preorder;

    }

}
View Code

学习之处:

  • 二叉树是有两个叉的树 二分查找树是满足左子树<节点<右子树 二叉平衡树 左子树和右子树的高度相差最大为1

你可能感兴趣的:(binary)