/** * Definition for a Node. * class Node { * public int val; * public Node left; * public Node right; * public Node next; * * public Node() {} * * public Node(int _val) { * val = _val; * } * * public Node(int _val, Node _left, Node _right, Node * _next) { * val = _val; * left = _left; * right = _right; * next = _next; * } * }; */
classSolution { public Node connect(Node root) { NodelevelStart= root; while (levelStart != null) { Nodecur= levelStart; while (cur != null) { if (cur.left != null) { cur.left.next = cur.right; if (cur.next != null) { cur.right.next = cur.next.left; } } cur = cur.next; } levelStart = levelStart.left; } return root; } }
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:
1 2 3 4
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
注意:
所有节点的值都是唯一的。
p和q不同,并且两个值都将存在于二叉树中。
java 参考代码:
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root == p || root == q) { return root; } TreeNodeleft= lowestCommonAncestor(root.left, p, q); TreeNoderight= lowestCommonAncestor(root.right, p, q); if (left != null && right != null) { return root; } return left != null ? left : right; } }
python 参考代码:
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: deflowestCommonAncestor(self, root, p, q): ifnot root or root == p or root == q: return root
left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q)
// Encodes a tree to a single string. public String serialize(TreeNode root) { StringBuildersb=newStringBuilder(); serialize(root, sb); return sb.toString(); }
// Decodes your encoded data to tree. public TreeNode deserialize(String data) { LinkedList<String> queue = newLinkedList<>(Arrays.asList(data.split(DELIMITER))); return deserialize(queue); }
classCodec: defserialize(self, root: TreeNode) -> str: """Encodes a tree to a single string. Args: root (TreeNode): the root of tree Returns: str: a serial str of binary tree """ res = [] self._serial(root, res) return','.join(res)
defdeserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree. Args: data (str): a serial str of binary tree Returns: TreeNode: the root of tree """ data = data.split(',') data.reverse() return self._deserial(data)
def_deserial(self, data: List[str]) -> TreeNode: val = data.pop() if val == '#': return