美文网首页算法提高之LeetCode刷题数据结构和算法分析笔试&&面试经验
先序遍历(前序遍历)递归和非递归-Java-LeetCode14

先序遍历(前序遍历)递归和非递归-Java-LeetCode14

作者: yang_zcybb | 来源:发表于2019-06-08 09:07 被阅读1次
        //前序遍历递归
        public List<Integer> preorderTraversal_1(TreeNode root) {
            LinkedList<Integer> ans = new LinkedList<>();
            if(root == null)
                return ans;
            subPreorderTraversal(root, ans);
            return ans;
        }
        private void subPreorderTraversal(TreeNode root, List<Integer> list){
            if(root == null){
                return;
            }
            list.add(root.val);
            subPreorderTraversal(root.left, list);
            subPreorderTraversal(root.right, list);
        }
    
    
        //前序遍历非递归,放入栈的顺序是:初始化是root,然后按照右、左的顺序放入
        public List<Integer> preorderTraversal_2(TreeNode root) {
            LinkedList<Integer> ans = new LinkedList<>();
            if(root == null)
                return ans;
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            while(!stack.empty()){
                TreeNode tmp = stack.pop();
                ans.add(tmp.val);
                if(tmp.right != null)
                    stack.push(tmp.right);
                if(tmp.left != null)
                    stack.push(tmp.left);
            }
            return ans;
        }
    

    相关文章

      网友评论

        本文标题:先序遍历(前序遍历)递归和非递归-Java-LeetCode14

        本文链接:https://www.haomeiwen.com/subject/ipgbxctx.html