【= 合并二叉树 =】
题目描述
解题思路
这个很简单,就是递归不断搜索同位置的不同二叉数的值并相加
解题方法
- PHP
function mergeTrees($root1, $root2) {
if($root1 == null) return $root2;
if($root2 == null) return $root1;
$root1->val += $root2->val;
$root1->left = $this->mergeTrees($root1->left, $root2->left);
$root1->right = $this->mergeTrees($root1->right, $root2->right);
return $root1;
}
- GO
func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode {
if(root1 == nil) {
return root2
}
if(root2 == nil) {
return root1
}
root1.Val += root2.Val
root1.Left = mergeTrees(root1.Left, root2.Left)
root1.Right = mergeTrees(root1.Right, root2.Right)
return root1
}
【= 填充每个节点的下一个右侧节点指针 =】
题目描述
解题思路 🤔🤔🤔
题目给出的完美二叉数: 遍历每层节点并查看其next节点
情况1:连接同一个父节点的两个子节点 node.left.next = node.right
情况2:连接不同父节点的两个子节点 node.right.next = node.next.left
请注意如果找不到下一个右侧节点,则next设置为null
解题方法
- PHP
public function connect($root) {
if($root->left == null) return $root;
$root->left->next = &$root->right;
if($root->next == null) {
$root->right->next = null;
} else {
$root->right->next = &$root->next->left;
}
$root->left = $this->connect($root->left);
$root->right = $this->connect($root->right);
return $root;
}
- GO
func connect(root *Node) *Node {
if root == nil || root.Left == nil {
return root
}
root.Left.Next = root.Right
if root.Next != nil {
root.Right.Next = root.Next.Left
}
connect(root.Left)
connect(root.Right)
return root
}