• leetcode -- Binary Tree Preorder Traversal


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

    For example:
    Given binary tree {1,#,2,3},

       1
        
         2
        /
       3
    

    return [1,2,3].

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

    [解题思路]

    递归解法

     1 public ArrayList<Integer> preorderTraversal(TreeNode root) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         ArrayList<Integer> result = new ArrayList<Integer>();
     5         
     6         preorder(root, result);
     7         
     8         return result;
     9     }
    10     
    11     public void preorder(TreeNode root, ArrayList<Integer> result){
    12         if(root != null){
    13             result.add(root.val);
    14             preorder(root.left, result);
    15             preorder(root.right, result);
    16         }
    17     }

    [非递归解法]

    1)访问节点cur,并将节点cur入栈;

    2)判断节点cur的左孩子是否为空,若为空,则取栈顶节点并进行出栈操作,并将栈顶节点的右孩子置为当前节点cur,循环至1);若不为空,则将cur的左孩子置为当前节点cur;

    3)知道cur为null并且栈为空,则遍历结束

     1 public ArrayList<Integer> preorderTraversal(TreeNode root) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         ArrayList<Integer> result = new ArrayList<Integer>();
     5         if(root == null){
     6             return result;
     7         }
     8         
     9         Stack<TreeNode> stack = new Stack<TreeNode>();
    10         TreeNode cur = root;
    11         while(cur != null || !stack.empty()){
    12             
    13             while(cur != null){
    14                 result.add(cur.val);
    15                 stack.push(cur);
    16                 cur = cur.left;
    17             }
    18             
    19             if(!stack.empty()){
    20                 cur = stack.pop();
    21                 // if(cur.right != null){
    22                     cur = cur.right;
    23                 // }
    24             }
    25         }
    26         
    27         return result;
    28     }
  • 相关阅读:
    django之上传
    djano的ORM操作
    Python中的分页管理
    MySQL作业
    socket操作
    python的os模块
    django-debug-toolbar的配置及使用
    logging模板及配置说明
    使用StrictRedis连接操作有序集合
    学习总结
  • 原文地址:https://www.cnblogs.com/feiling/p/3426172.html
Copyright © 2020-2023  润新知