二叉树
Y·Not·Try
这个作者很懒,什么都没留下…
展开
-
二叉树和N叉树的后序遍历
二叉树:class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: if not(root): return [] stack = [root] res = [] while(stack): cur_node = stack.pop() res.append(cur原创 2020-09-09 15:17:11 · 89 阅读 · 0 评论 -
二叉树和N叉树的前序遍历
二叉树:class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: if not(root): return [] stack = [root] res = [] while(stack): cur_node = stack.pop() res.append(cur_原创 2020-09-09 15:03:15 · 127 阅读 · 0 评论 -
向二叉搜索树中插入节点
向二叉搜索树插入节点需要保持其本身的性质,即节点左子树的节点值皆小于其根节点的值,节点右子树的节点值皆大于其根节点的值。这里使用递归解决class Solution{ public TreeNode insert(TreeNode root, TreeNode node){ if(root == null){ return node; } // 此时遍历到空引用,返回节点node引用即可 if(node.val <原创 2020-06-22 20:17:48 · 359 阅读 · 0 评论 -
递归求二叉树的高度
此问题可拆解为求左右子树最高的高度加1,递归出口为访问到叶子节点本身时其高度为1,此时返回0即可。class Solution{ public int height(TreeNode root){ if(root == null){ return 0; } return Math.max(height(root.left),height(root.right)) + 1; }}由于使用了递归,内存开销巨大原创 2020-06-22 15:16:38 · 860 阅读 · 0 评论 -
递归求二叉树叶子节点和
使用递归解决此类问题,可以首先分析问题及其拆解,这里面可以将求叶子节点的和拆解为求左子树叶子节点和与求右子树的叶子节点和,然后分析递归出口,这里即访问到叶子节点退出,返回叶子节点本身的值。class Solution{ public int leafsum(TreeNode root){ if(root == null){ return 0; } if(root.left == null && root.r原创 2020-06-22 14:47:17 · 756 阅读 · 0 评论