美文网首页
145二叉树的后序遍历

145二叉树的后序遍历

作者: 天山童姥张奶奶 | 来源:发表于2020-04-18 13:29 被阅读0次

给定一个二叉树,返回它的 后序 遍历。
示例:

输入: [1,null,2,3]
1

2
/
3

输出: [3,2,1]

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
递归
class Solution {
    List<Integer> lists = new ArrayList<>();
    public List<Integer> postorderTraversal(TreeNode root) {
        if(root == null) return lists;
        postorderTraversal(root.left);
        postorderTraversal(root.right);
        lists.add(root.val);
        return lists;
    }
}
class Solution {
  public List<Integer> postorderTraversal(TreeNode root) {
    LinkedList<TreeNode> stack = new LinkedList<>();
    LinkedList<Integer> output = new LinkedList<>();
    if (root == null) {
      return output;
    }
    stack.add(root);
    while (!stack.isEmpty()) {
      TreeNode node = stack.pollLast();
      output.addFirst(node.val);
      if (node.left != null) {
        stack.add(node.left);
      }
      if (node.right != null) {
        stack.add(node.right);
      }
    }
    return output;
  }
}

非递归
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ans = new LinkedList<>();
        if (root == null) return ans;
    
        Stack <TreeNode> stack = new Stack<>();
        stack.push(root);
        TreeNode node;
        while (!stack.isEmpty()) {
            node = stack.pop();
            ans.add(0, node.val);
            if (node.left != null) {
                stack.push(node.left);
            }
            if (node.right != null) {
                stack.push(node.right);
            }
        }
        return ans;
    }
}

相关文章

网友评论

      本文标题:145二叉树的后序遍历

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