摘要:本文主要向大家介绍了C++语言相关知识代码:二叉树(LEETCODE),通过具体的内容向大家展示,希望对大家学习C++语言有所帮助。
本文主要向大家介绍了C++语言相关知识代码:二叉树(LEETCODE),通过具体的内容向大家展示,希望对大家学习C++语言有所帮助。
0、二叉树最大深度
原题目:Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
方法:求最大深度的时候,只需要比较左右子树的深度,取较大者+1就行了
C++代码:
class Solution
{public:
int minDepth(TreeNode *root){
if(root==Null) return 0;
int l=minDepth(root->left);
int r=minDepth(root->right);
if(l==0||r==0)
return 1+l+r;
return 1+min(l,r);
}
};
1、二叉树最小深度
原题目:Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
方法:求最小深度的时候,需要区分双子树与单子树,双子树时,深度较小者+1,单子树时(即左右子树有一颗为空时)为深度较大者+1
C++代码:
class Solution{
public:
int maxDepth(TreeNode *root){
if (root==NULL)
{
return 0;
}
int l=maxDepth(root->left);
int r=maxDepth(root->right);
return 1+max(l,r);
}
};
2、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?
方法:后序遍历,使用vector栈来做,先将父节点入栈,再将右孩子入栈,左孩子入栈。那么返回时就能可以倒序输出后序遍历值。
class Solution{
public:
void postOrder(TreeNode *root,vector<int>&vec){
if (root!=NULL)
{
postOrder(root->left,vec);
postOrder(root->right,vec);
vec.push_back(root->val);
}
}
vector<int>postorderTraversal(TreeNode *root){
vector<int> vec;
postOrder(root,vec);
return vec;
}
};
本文由职坐标整理并发布,了解更多内容,请关注职坐标编程语言C/C+频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号