博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode:binary-tree-postorder-traversal
阅读量:4180 次
发布时间:2019-05-26

本文共 1608 字,大约阅读时间需要 5 分钟。

题目描述:树的后序遍历

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].

实现:

1.递归方式

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    void postOrder(TreeNode *root,vector
&vec){ if(root != NULL){//递归实现,比较简单 postOrder(root->left,vec); postOrder(root->right,vec); vec.push_back(root->val); } } vector
postorderTraversal(TreeNode *root) { vector
vec; postOrder(root,vec); return vec; }};
2.非递归方式

需要用栈来保存每次的父节点

class Solution {public:      vector
postorderTraversal(TreeNode *root) { vector
vec; if(root == NULL) return vec; stack
st; st.push(root); TreeNode * cur = NULL; while(!st.empty()){ cur = st.top(); if(cur->left == NULL && cur->right == NULL){ vec.push_back(cur->val); st.pop(); }else{//进入栈的每个节点都没有左右节点,这样就可以直接出栈 if(cur->right){//将访问过的右节点置为空 st.push(cur->right); cur->right = NULL; } if(cur->left){//
将访问过的左节点置为空 st.push(cur->left); cur->left = NULL; } } } return vec; }};

转载地址:http://dohai.baihongyu.com/

你可能感兴趣的文章
实模式,保护模式与V86模式
查看>>
628. Maximum Product of Three Numbers(排序)
查看>>
Linux内核-------同步机制(二)
查看>>
面试题31-------连续子数组的最大和(数组)
查看>>
epoll 实现Chat
查看>>
21. Merge Two Sorted Lists(链表)
查看>>
2. Add Two Numbers(链表)
查看>>
637. Average of Levels in Binary Tree(Tree)
查看>>
226. Invert Binary Tree(Tree)
查看>>
328. Odd Even Linked List(链表)
查看>>
199. Binary Tree Right Side View(Tree)
查看>>
230. Kth Smallest Element in a BST(Tree)
查看>>
求字符串的最长回文串-----Manacher's Algorithm 马拉车算法
查看>>
回溯法常用的解题模板和常见题型
查看>>
深入分析Java I/O 的工作机制
查看>>
动态规划的套路----左神
查看>>
KMP算法简解
查看>>
左神算法课进阶版总结
查看>>
左神算法基础班总结
查看>>
Linux性能优化
查看>>