zoukankan      html  css  js  c++  java
  • [leetcode]Binary Tree Postorder Traversal

    Binary Tree Postorder Traversal

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

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

       1
        
         2
        /
       3
    

    return [3,2,1].

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

    算法思路:

    最简单的后序遍历。不解释了。

    代码如下:

     1 public class Solution {
     2     List<Integer> res = new ArrayList<Integer>();
     3     public List<Integer> postorderTraversal(TreeNode root) {
     4         if(root == null) return res;
     5         if(root.left != null) postorderTraversal(root.left);
     6         if(root.right != null) postorderTraversal(root.right);
     7         res.add(root.val);
     8         return res;
     9     }
    10 }

    非递归实现:

    需要两个栈,一个数字栈用来记录后序遍历的逆序,一个节点栈来遍历整棵树,如果不明白也没关系,有个绝招!背下来吧。。。。

    代码如下:

    public class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<Integer>();
            if(root == null) return res;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            Stack<Integer> intStack = new Stack<Integer>();
            stack.push(root);
            while(!stack.isEmpty()){
                TreeNode node = stack.pop();
                intStack.push(node.val);
                if(node.left != null) stack.push(node.left);
                if(node.right != null) stack.push(node.right);
            }
            while(!intStack.isEmpty()){
                res.add(intStack.pop());
            }
            return res;
        }
    }
  • 相关阅读:
    UVa 839 -- Not so Mobile(树的递归输入)
    UVa 548 -- Tree
    UVA 122 -- Trees on the level (二叉树 BFS)
    UVa679 小球下落(树)
    POJ 2255 -- Tree Recovery
    POJ 1451 -- T9
    POJ 2513 -- Colored Sticks
    STL -- heap结构及算法
    nginx利用try_files实现多个源
    nginx location的优先级
  • 原文地址:https://www.cnblogs.com/huntfor/p/3900239.html
Copyright © 2011-2022 走看看