首页 > 其他 > 详细

144. 二叉树的前序遍历

时间:2021-09-02 01:23:13      阅读:15      评论:0      收藏:0      [点我收藏+]

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?

二叉树的先序遍历。

这个比较简单,直接看递归和非递归的代码实现

class Solution {
    
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list=new ArrayList<>();
         process(root,list);
         return list;

    }

    public void process(TreeNode node,List<Integer> list){
        if(node==null){
            return;
        }
        list.add(node.val);
        process(node.left,list);
        process(node.right,list);
    }
}

先序遍历:中左右
非递归的方式用stack来实现(深度优先遍历用stack,广度优先用队列)
对当前节点压入stack,弹出并打印(中),再对cur压入右左(左右)
class Solution {

    public List<Integer> preorderTraversal(TreeNode root) {
         List<Integer> list=new ArrayList<>();
        if(root==null){
            return list;
        }
        Stack<TreeNode> stack=new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()){
           TreeNode cur=stack.pop();
           list.add(cur.val);
           if(cur.right!=null){
               stack.push(cur.right);
           }
           if(cur.left!=null){
               stack.push(cur.left);
           }
        }
        return list;
    }
}

  

 

144. 二叉树的前序遍历

原文:https://www.cnblogs.com/iwyc/p/15210915.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!